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
}
];
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With