0

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.

5
  • 7
    array.sort((a, b) => a.id - b.id) Commented Oct 19, 2016 at 0:07
  • 1
    MDN documentation explains it pretty well. Commented Oct 19, 2016 at 0:09
  • @AndrewLi Yup, the only difference being that instead of returning a - b, since the array contains objects you would return a.id - b.id Commented Oct 19, 2016 at 0:11
  • 1
    @RohanRao I never said the documentation gave an exact solution; I said it explained the sort function. They OP can apply it to their needs Commented Oct 19, 2016 at 0:12
  • @choz make an answer so I can accept it Commented Oct 19, 2016 at 0:19

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.