0

I have a Javascript Object in the format key:pair where the pair is an array containing 2 timestamp values. I would like to sort this object so that the elements with the lowest numbers (earliest times) are displayed first.

Here is an example of the object: {"21_2":[1409158800,1409160000],"20_1":[1409148000,1409149200],"56_1":[1409149800,1409151600]}

So in this case, I would want the final sorted object to read:

{"20_1":[1409148000,1409149200],"56_1":[1409149800,1409151600],"21_2":[1409158800,1409160000]}

Obviously the sort() function will come into play here for the arrays, but how do I access those values inside the object? Note the object key isn't actually an integer because of the underscore.

I have found this: Sort Complex Array of Arrays by value within but haven't been able to apply it to my situation. Any help would be greatly appreciated.

Community
  • 1
  • 1
Ty Bailey
  • 2,392
  • 11
  • 46
  • 79
  • 2
    You can't sort JavaScript Objects. Only arrays can be sorted. – Cerbrus Aug 27 '14 at 14:06
  • That aside, what are you trying to do? This question might help: http://stackoverflow.com/questions/890807/iterate-over-a-javascript-associative-array-in-sorted-order – Cerbrus Aug 27 '14 at 14:07
  • possible duplicate of [Sorting JavaScript Object by property value](http://stackoverflow.com/questions/1069666/sorting-javascript-object-by-property-value) – Fractaliste Aug 27 '14 at 14:09
  • @Cerbrus we can't put that aside, the question goes to an end here **You can't sort JavaScript Objects**, *Until you change that to array* – Mritunjay Aug 27 '14 at 14:09
  • What is the end goal of "sorting" this object? By saying "I want the final sorted object to read" you are basically saying you want to modify the `toString()` function. – Alex W Aug 27 '14 at 14:16

1 Answers1

2

You could change the structure of your data like this:

var myArray = [{
        "id" : "21_2" // id or whatever these are
        "timeStamps" : [1409158800,1409160000]
    }, {
        "id" : "20_1"
        "timeStamps" : [1409148000,1409149200]
    }];

Then you could sort it by the regular array sort:

myArray.sort(function(a, b){
    // however you want to compare them:
    return a.timeStamps[0] - b.timeStamps[0]; 
});
Balázs Édes
  • 13,452
  • 6
  • 54
  • 89