Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
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: stackoverflow.com/questions/890807/… –  Cerbrus Aug 27 '14 at 14:07
    
possible duplicate of 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 Answer 1

up vote 2 down vote accepted

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]; 
});
share|improve this answer
    
This is what I was looking for. Thank you. –  Ty Bailey Aug 27 '14 at 14:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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