Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Sort array of objects by single key with date value

I have an array of objects with several key value pairs, and I need to sort them based on 'updated_at':
[
{
"updated_at" : "2012-01-01T06:25:24Z",
"foo" : "bar"
},
{
"updated_at" : "2012-01-09T11:25:13Z",
"foo" : "bar"
},
{
"updated_at" : "2012-01-05T04:13:24Z",
"foo" : "bar"
}
]


What's the most efficient way to do so?
by

2 Answers

vishaljlf39
You can use Array.sort.

Here's an example:
var arr = [{
"updated_at": "2012-01-01T06:25:24Z",
"foo": "bar"
},
{
"updated_at": "2012-01-09T11:25:13Z",
"foo": "bar"
},
{
"updated_at": "2012-01-05T04:13:24Z",
"foo": "bar"
}
]

arr.sort(function(a, b) {
var keyA = new Date(a.updated_at),
keyB = new Date(b.updated_at);
// Compare the 2 dates
if (keyA < keyB) return -1;
if (keyA > keyB) return 1;
return 0;
});

console.log(arr);
pankajshivnani123
With ES2015 support it can be done by:

foo.sort((a, b) => a.updated_at < b.updated_at ? -1 : 1)

Login / Signup to Answer the Question.