Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a Javascript object by value

In my Javascript application I have an Object and I need to be able to order the array by a value within the Inner Object.

For example:

{
    a : {
        timestamp: xxxxxx
        other : yyyyyy
    },
    b : {
        timestamp: xxxxxx
        other : yyyyyy
    },
    c : {
        timestamp: xxxxxx
        other : yyyyyy
    }
}

What I need to do is manage this data set and re-order the array according to the timestamp of each inner object.

What ways are they that I can do to do this?

update:

My initial thought would be doing something like so:

{
    a : {},
    b : {},
    c : {},
    _ : [
        c, a, b //Key's Only
    ]
}

Then re-indexing the the object based on those values, that would sort out how to index the object, but when I insert a new element i would also have to regenerate the _ index relationship which seems way to much effort.

like image 750
RobertPitt Avatar asked Dec 17 '22 09:12

RobertPitt


2 Answers

You can copy the data to an array and then sort it:

var data = {
    a : {
        timestamp: 11111,
        other : "xxx"
    },
    b : {
        timestamp: 22222,
        other : "yyy"
    },
    c : {
        timestamp: 33333,
        other : "zzz"
    }
};

var output = [];

// copy items to an array so they can be sorted
for (var key in data) {
    data[key].key = key;   // save key so you can access it from the array (will modify original data)
    output.push(data[key]);
}    

output.sort(function(a,b) {
    return(a.timestamp - b.timestamp);
});

Generates this as output (note I added the original key to the object so it's accessible from the array):

[{"timestamp":11111,"other":"xxx","key":"a"},
{"timestamp":22222,"other":"yyy","key":"b"},
{"timestamp":33333,"other":"zzz","key":"c"}]

You can see this working here: http://jsfiddle.net/jfriend00/hXpkP/

like image 190
jfriend00 Avatar answered Dec 30 '22 14:12

jfriend00


Javascript objects are not associative arrays. They may behave similarly, but they are not the same. Javascript has no associative arrays.

While associative arrays have a concept of order, Javascript objects simply do not share this particular feature with them. Objects, by there very nature, are not ordered.

So, to answer your question: you cannot order them...

like image 30
Joseph Silber Avatar answered Dec 30 '22 15:12

Joseph Silber