EN
JavaScript - sort array of objects by ISO 8601 date string property value
0 points
In this article, we would like to show you how to sort array of objects by ISO 8601 date string property value in JavaScript.
Quick solution:
xxxxxxxxxx
1
array.sort(function(a, b) {
2
return a.dateProperty.localeCompare(b.dateProperty);
3
});
Note: it works only when we use ISO 8601 date strings in UTC variant (ended with
Z
).
or:
xxxxxxxxxx
1
array.sort(function(a, b) {
2
var aDate = new Date(a.birthday);
3
var bDate = new Date(b.birthday);
4
return aDate.getTime() - bDate.getTime();
5
});
Note: it shoulod be used when ISO 8601 date strings may contain timezone offset (ended with
+XX:YY
or-XX:YY
).
In this example, we sort an array of objects by date
property value using the custom compare function as an argument of the sort()
method.
In this example, we use an embedded String
localeCompare()
method.
xxxxxxxxxx
1
var array = [
2
{ name: 'Ann', birthday: '2000-01-02T00:00:00Z' },
3
{ name: 'Tom', birthday: '2000-01-01T00:00:00Z' },
4
{ name: 'Mark', birthday: '2000-01-03T00:00:00Z' }
5
];
6
7
array.sort(function(a, b) {
8
return a.birthday.localeCompare(b.birthday);
9
});
10
11
console.log(JSON.stringify(array, null, 4));
Comparison using Date
objects:
xxxxxxxxxx
1
var array = [
2
{ name: 'Ann', birthday: '2000-01-02T00:00:00Z' },
3
{ name: 'Tom', birthday: '2000-01-01T00:00:00Z' },
4
{ name: 'Mark', birthday: '2000-01-03T00:00:00Z' }
5
];
6
7
array.sort(function(a, b) {
8
var aDate = new Date(a.birthday);
9
var bDate = new Date(b.birthday);
10
return aDate.getTime() - bDate.getTime();
11
});
12
13
console.log(JSON.stringify(array, null, 4));
xxxxxxxxxx
1
var array = [
2
{ name: 'Ann', birthday: '2000-01-02T00:00:00Z' },
3
{ name: 'Tom', birthday: '2000-01-01T00:00:00Z' },
4
{ name: 'Mark', birthday: '2000-01-03T00:00:00Z' }
5
];
6
7
array.sort(function(a, b) {
8
return b.birthday.localeCompare(a.birthday);
9
});
10
11
console.log(JSON.stringify(array, null, 4));
or:
xxxxxxxxxx
1
var array = [
2
{ name: 'Ann', birthday: '2000-01-02T00:00:00Z' },
3
{ name: 'Tom', birthday: '2000-01-01T00:00:00Z' },
4
{ name: 'Mark', birthday: '2000-01-03T00:00:00Z' }
5
];
6
7
array.sort(function(a, b) {
8
var aDate = new Date(a.birthday);
9
var bDate = new Date(b.birthday);
10
return bDate.getTime() - aDate.getTime();
11
});
12
13
console.log(JSON.stringify(array, null, 4));