codenoob codenoob - 4 months ago 14
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.


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 -;

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