开发者

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 : 7开发者_如何转开发00, 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;
});


Actually now you have array from one pseudo-array object. But you could transform that object to real array, sort it, and then transform back:

var originalArray = [{
    1:{start : 60, end : 120},
    2:{start : 700, end : 720},
    3:{start : 100, end : 240}
}];
var pseudoArray = originalArray[0];
var arrayToSort = [];
for (var key in pseudoArray) {
    arrayToSort.push(pseudoArray[key]);
}
arrayToSort.sort(function(left, right) {
    return left.start - right.start || left.end - right.end;
});
var resultPseudoArray = {};
for (var i = 0; i < arrayToSort.length; i++) {
    resultPseudoArray[i + 1] = arrayToSort[i];
}
var resultArray = [resultPseudoArray];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜