codenoob codenoob - 1 month ago 8
Javascript Question

javascript rearrange array index based on value

I have an array that look like this

var array = [{id:5},{id:1},{id:2}]


I want to rearrange the array index based on the id value from lowest to highest so it becomes

var newarray = [{id:1},{id:2},{id:5}]


I have been looking at sort() but I dont quite understand the logic behind it.

Answer

To achieve this, you can use native array sort function which you can pass a callback as a compare function.

var array = [{id:5},{id:1},{id:2}];

array.sort(function(a, b) {
  return a.id - b.id;
});

console.log(array); //[{"id": 1 }, {"id": 2 }, {"id": 5 } ]

Comments