3

How can I sort this array based upon 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);

expected output

const arr = [
  {
    "id": 38938887,
    "subInternalUpdates": true
  },
{
    "id": 38938888,
    "subInternalUpdates": true,
  },
  {
    "id": 38938889,
    "subInternalUpdates": true
  }
];
dota2pro
  • 7,220
  • 7
  • 44
  • 79

2 Answers2

5

Much better return a.id - b.id when you order the array:

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);
Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30
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);
boxdox
  • 552
  • 2
  • 8