如何根据键对 JavaScript 对象数组进行排序

dot*_*pro 4 javascript

如何根据 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);
Run Code Online (Sandbox Code Playgroud)

预期产出

const arr = [
  {
    "id": 38938887,
    "subInternalUpdates": true
  },
{
    "id": 38938888,
    "subInternalUpdates": true,
  },
  {
    "id": 38938889,
    "subInternalUpdates": true
  }
];
Run Code Online (Sandbox Code Playgroud)

Gio*_*ito 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);
Run Code Online (Sandbox Code Playgroud)