如何按照某个键来对 JavaScript 对象数组进行排序

4

如何基于id对此数组进行排序?

const arr = [{
    "id": 38938888,
    "subInternalUpdates": true,
  },
  {
    "id": 38938887,
    "subInternalUpdates": true
  },
  {
    "id": 38938889,
    "subInternalUpdates": true
  }
];
const sorted_by_name = arr.sort((a, b) => a.id > b.id);
console.log(sorted_by_name);

预期输出

const arr = [
  {
    "id": 38938887,
    "subInternalUpdates": true
  },
{
    "id": 38938888,
    "subInternalUpdates": true,
  },
  {
    "id": 38938889,
    "subInternalUpdates": true
  }
];

你期望的结果匹配...不过,我会使用a.id - b.id代替。 - Bravo
我觉得你已经做了,问题出在哪里? - Seid Akhmed Agitaev
2
@SeidAkhmedAgitaev OP 的数组仍然没有排序。 - boxdox
2个回答

6

当对数组进行排序时,使用a.id - b.id可以获得更好的返回结果:

const arr = [{
    "id": 38938888,
    "subInternalUpdates": true,
  },
  {
    "id": 38938887,
    "subInternalUpdates": true
  },
  {
    "id": 38938889,
    "subInternalUpdates": true
  }
];
const sorted_by_name = arr.sort((a, b) => {
   return a.id - b.id;
});
console.log(sorted_by_name);


2

You can directly compare using a-b, otherwise, if you're comparing the values, you need to return -1, 0 or 1 for sort to work properly

const arr = [{
    "id": 38938888,
    "subInternalUpdates": true,
  },
  {
    "id": 38938887,
    "subInternalUpdates": true
  },
  {
    "id": 38938889,
    "subInternalUpdates": true
  }
];
const sorted_by_name = arr.sort((a, b) => a.id - b.id);
console.log(sorted_by_name);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接