'javascript sorting a json array by a given key [duplicate]
given
let jsons = [
{
"id": 10
...
},
{
"id": 4
...
},
{
"id": 1
...
},
...
]
I want jsons to be sorted by the id e.g.
let jsons = [
{
"id": 1
...
},
{
"id": 2
...
},
{
"id": 3
...
},
...
]
This is what I have done to do this (but its extremely inefficient)
let jsons = [
{
"id": 10
},
{
"id": 4
},
{
"id": 1
},
]
let new_list = []
length = jsons.length
for(let i = 0; i < length; i++) {
let index = 0
let cur_lowest = 50000 // not sure how to get an infinite upper_bound
for(let j = 0; j < jsons.length; j++) {
if(jsons[j].id <= cur_lowest) {
cur_lowest = jsons[j].id
index = j
}
}
new_list.push(jsons[index])
jsons.splice(index, 1)
}
console.log(new_list);
So this works I did it here https://jsfiddle.net/xceybhLg/5/
But is there a simpler way? Preferably with like the sorted function I think it can attach on keys but reading the documentation I don't really understand it
Solution 1:[1]
Why cant you use a simple sort function that accepts a list and the key against which the sort action is to be performed.
let jsons = [
{ "id": 10 },
{ "id": 4 },
{ "id": 1 },
];
function sortList(list, key) {
return list.sort((a, b) => a[key] - b[key]);
}
const new_list = sortList(jsons, 'id');
console.log(new_list);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nitheesh |
