How do I sort this array?
[
{id : 1, start : 60, end : 120},
{id : 2, start : 100, end : 240},
{id : 3, start : 700, end : 720}
]
UPDATE: So if my array looks like this, can I sort it based on start value?
[{
1:{start : 60, end : 120},
2:{start : 100, end : 240},
3:{start : 700, end : 720}
}]
What you have there is an array of objects. You must specify how you want to sort it.
Anyway, you can use the sort method:
var data = [{id : 1, start : 60, end : 120}, {id : 2, start : 100, end : 240},{id : 3, start : 700, end : 720}];
function sortByStart(a, b){
return a.start - b.start;
}
data.sort(sortByStart);
You may want a way to sort objects that may have the same start value:
[
{id : 1, start : 60, end : 120},
{id : 2, start : 100, end : 240},
{id : 3, start : 700, end : 720}
]
A.sort(function(a, b){
return a.start-b.start || a.end-b.end || a.id-b.id;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With