1
1

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}
}]
flag

79% accept rate
5  
Sort by what? .. – Andreas Bonini Dec 22 '09 at 20:03

3 Answers

11

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);
link|flag
8  
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 Dec 22 '09 at 20:06
1  
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 Dec 22 '09 at 20:20
+1 Seb + 1 Techpriester. – David Robbins Dec 22 '09 at 20:22
0

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;
});
link|flag
0

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];
link|flag

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.