1

I am making a game and I want to sort the scoreboard by the highest score and lowest time if the scores are the same. However I do not know how to do so, I have tried .sort() but I don't think it works for objects, please help thanks. Below shows the array with the information of users.

[
  { score: 2, userName: 'adam', time: '0:20' },
  { score: 4, userName: 'john', time: '0:45' },
  { score: 1, userName: 'kevin', time: '0:30' },
  { score: 8, userName: 'james', time: '0:20' },
]
NixyCron
  • 61
  • 3
  • this will help you sir https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value – kennethreyt Jul 30 '20 at 05:56
  • 3
    Does this answer your question? [Sorting an array of objects by property values](https://stackoverflow.com/questions/979256/sorting-an-array-of-objects-by-property-values) – Sivakumar Tadisetti Jul 30 '20 at 06:00

3 Answers3

3

check this, you can use compare by adding a condition

const myarr = [
  { score: 2, userName: "adam", time: "0:20" },
  { score: 4, userName: "john", time: "0:45" },
  { score: 1, userName: "kevin", time: "0:30" },
  { score: 8, userName: "james", time: "0:20" },
];

const output = myarr.sort((a, b) => a.score -b.score );

console.log(output);
kennethreyt
  • 161
  • 2
  • 10
0

Better scores are at the top, but in case of a tie, shortest time wins.

I modified the data to better illustrate this.

const array = [
  { score: 4, userName: 'adam', time: '0:20' },
  { score: 4, userName: 'john', time: '0:45' },
  { score: 4, userName: 'kevin', time: '0:30' },
  { score: 8, userName: 'james', time: '0:30' },
].sort((a, b) => a.score < b.score ? 1 : a.score > b.score ? -1 : a.time > b.time ? 1 : a.time < b.time ? -1 : 0);

console.log(array);
GirkovArpa
  • 4,427
  • 4
  • 14
  • 43
0

const arr = [
  { score: 2, userName: "adam", time: "0:20" },
  { score: 4, userName: "john", time: "0:45" },
  { score: 1, userName: "kevin", time: "0:30" },
  { score: 8, userName: "james", time: "0:20" },
];

const output = arr.sort((a, b) => a.score -b.score );

console.log(output);