Skip to content

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?

Answer

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]