codenoob
codenoob

Reputation: 539

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.

Upvotes: 0

Views: 58

Answers (1)

choz
choz

Reputation: 17858

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 } ]

Upvotes: 2

Related Questions