Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript sorting a json array by a given key

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading