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.

5
  • 2
    You can't sort JavaScript Objects. Only arrays can be sorted. Commented Aug 27, 2014 at 14:06
  • That aside, what are you trying to do? This question might help: stackoverflow.com/questions/890807/… Commented Aug 27, 2014 at 14:07
  • possible duplicate of Sorting JavaScript Object by property value Commented Aug 27, 2014 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 Commented Aug 27, 2014 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. Commented Aug 27, 2014 at 14:16

1 Answer 1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.