0

I have following array:

var events = [
 {id : 1, start : 100, end : 120},
 {id : 2, start : 60, end : 240},
 {id : 3, start : 700, end : 720}
];

How do I sort based on start index while preserving the id something like:

var events = [
 {id : 2, start : 60, end : 240},
 {id : 1, start : 100, end : 120},
 {id : 3, start : 700, end : 720}
];

I tried:

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

But neither worked :(

asked May 13, 2012 at 7:19
1

1 Answer 1

3

The array.sort(..) function passes two elements of the array (which are being compared) to the comparator function you specify. Since, in that case, a and b are objects like {id : 3, start : 700, end : 720}, they can not be really compared like a-b.

Use this instead:

events.sort(function(a,b){return a.start - b.start;});
answered May 13, 2012 at 7:24
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.