Jordi Romeu
Jordi Romeu

Reputation: 117

How to get the last item in an object by sorted key order

Suppose I have an object with this structure:

{
        "friends_count": {
            "1420800660": 49391,
            "1421149814": 49344,
            "1421149955": 49344
        }
}

In the object, the first number (the key) is a timestamp. The second number is the value. I want to get the most recent item of that object. So, I need to get the key that is closest in time. How do I have to do it?

Upvotes: 3

Views: 5287

Answers (2)

Amit Joki
Amit Joki

Reputation: 59282

So, I need to get the key that is closest in time

Sure. Just call Object.keys on obj.friends_count and then sort

var key = Object.keys(obj.friends_count).sort()[0];

Object.keys returns an array of keys of the provided object and Array.sort will sort it in ascending order and [0] will take the first element of the sorted array.

Just Array.sort will work fine here since they are of the same length and everything should be fine. If you want to be more clear, then it would be arr.sort(function(a, b){ return a - b })[0]

Upvotes: 3

Simon Staton
Simon Staton

Reputation: 4505

If you are wanting to get the latest from the key timestamp then just convert it to a date:

var something = {
            "friends_count": {
                "1420800660": 49391,
                "1421149814": 49344,
                "1421149955": 49344
            }
    },
    dateCheck,
    newest;

for(var key in something.friends_count){
    if(!dateCheck || new Date(key*1000) > dateCheck){
        dateCheck = new Date(key*1000);
        newest = something.friends_count[key];
    }
}

console.log(newest);

http://jsfiddle.net/w4dsk4m3/

Upvotes: 1

Related Questions