2

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

3 Answers 3

17

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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

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;
});

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.