Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort javascript array of objects, based upon a key [duplicate]

Tags:

javascript

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
  }
];
like image 929
dota2pro Avatar asked Sep 04 '25 16:09

dota2pro


2 Answers

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);
like image 138
Giovanni Esposito Avatar answered Sep 07 '25 08:09

Giovanni Esposito


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);
like image 22
boxdox Avatar answered Sep 07 '25 08:09

boxdox