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 :(

Dev555
  • 2,128
  • 4
  • 30
  • 40
  • Possible duplicate of [Sorting an array of JavaScript objects](http://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects) – diziaq Dec 02 '15 at 05:22

1 Answers1

5

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;});
UltraInstinct
  • 43,308
  • 12
  • 81
  • 104