views:

188

answers:

3

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}
}]
+11  A: 

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);
Seb
You don't even need to name the comparison function. You could use it as an anonymous function if you don't need the comparisons elsewhere.data.sort( function (a,b) {return a.id -b.id; };
Techpriester
Yeah, absolutely, but I always try to avoid anonymous functions since they make the code harder to read - you know, programmers spend more time reading code than writing it :)
Seb
+1 Seb + 1 Techpriester.
David Robbins
A: 

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;
});
kennebec
A: 

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];
BaykaJIak