I have an array of objects with several key value pairs, and I need to sort them based on ‘updated_at’:
JavaScript
x
15
15
1
[
2
{
3
"updated_at" : "2012-01-01T06:25:24Z",
4
"foo" : "bar"
5
},
6
{
7
"updated_at" : "2012-01-09T11:25:13Z",
8
"foo" : "bar"
9
},
10
{
11
"updated_at" : "2012-01-05T04:13:24Z",
12
"foo" : "bar"
13
}
14
]
15
What’s the most efficient way to do so?
Advertisement
Answer
You can use Array.sort
.
Here’s an example:
JavaScript
1
24
24
1
var arr = [{
2
"updated_at": "2012-01-01T06:25:24Z",
3
"foo": "bar"
4
},
5
{
6
"updated_at": "2012-01-09T11:25:13Z",
7
"foo": "bar"
8
},
9
{
10
"updated_at": "2012-01-05T04:13:24Z",
11
"foo": "bar"
12
}
13
]
14
15
arr.sort(function(a, b) {
16
var keyA = new Date(a.updated_at),
17
keyB = new Date(b.updated_at);
18
// Compare the 2 dates
19
if (keyA < keyB) return -1;
20
if (keyA > keyB) return 1;
21
return 0;
22
});
23
24
console.log(arr);