根据对象中的值对对象数组进行排序

时间:2020-07-30 05:53:55

标签: javascript

我正在做一个游戏,如果分数相同,我想按最高分数和最短时间对记分板进行排序。但是我不知道该怎么做,我尝试了.sort(),但是我认为它不适用于对象,请帮忙谢谢。下面显示了包含用户信息的数组。

modal div

3 个答案:

答案 0 :(得分:3)

选中此项,您可以通过添加条件来使用比较

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);

答案 1 :(得分:0)

更好的分数是最高的,但是如果出现平局,则以最短的时间获胜。

我修改了数据以更好地说明这一点。

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);

答案 2 :(得分: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);

相关问题