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 🙁
The
array.sort(..)function passes two elements of the array (which are being compared) to the comparator function you specify. Since, in that case,aandbare objects like{id : 3, start : 700, end : 720}, they can not be really compared likea-b.Use this instead: