Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort this array in JavaScript?

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}
}]
like image 588
priyank Avatar asked Jul 12 '26 00:07

priyank


2 Answers

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);
like image 183
Seb Avatar answered Jul 13 '26 14:07

Seb


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;
});
like image 28
kennebec Avatar answered Jul 13 '26 13:07

kennebec