I have an array of objects like:
[
{date: "2016-01-07T15:01:51+00:00", text: "Lorem ipsum"},
{date: "2016-22-08T15:04:36+00:00", text: "dolor"},
// etc.
]
How's the best way to sort these by the date property? I'm already mapping this array to a react component, so any solution that works within the map function I guess would be preferred, but not essential.
I'm trying to use the sort()
method at the moment, but can't work how to feed it the date property.
asked Jan 27, 2016 at 14:13
1 Answer 1
You can have a custom sort function:
var data = [{
date: "2016-07-01T15:01:51+00:00",
text: "Lorem ipsum"
}, {
date: "2016-02-22T15:04:36+00:00",
text: "dolor"
}, {
date: "2015-08-22T15:04:36+00:00",
text: "test"
}]
var result = data.sort(function(a, b) {
var date1 = new Date(a.date);
var date2 = new Date(b.date);
console.log(date1, date2);
return (+date1 - +date2);
});
console.log(result)
georg
216k57 gold badges322 silver badges401 bronze badges
answered Jan 27, 2016 at 14:16
5 Comments
Rajesh Dixit
@georg, what is the difference between
return (a-b)
and return (a>b)
. Isn't sort considers -ve
value as false and +ve
value as true? I may be wrong. Just wanted to confirm.georg
You have to return -1, 0, or 1 from the sort callback, not true/false.
suryanaga
@georg Thanks, what do the -1, 0, or 1 values correspond to?
Rajesh Dixit
@sanjaypoyzer I guess less than, equal and greater than.
georg
@sanjaypoyzer: when comparing a to b, return -1 (or any negative) if a < b, +1 (or any positive) if a > b, and 0 if they are equal, see developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
lang-js
date1.localeCompare(date2)
in your sort callback.arr.sort((a,b) => a.date.localeCompare(b.date))
"2016-22-08T15:04:36+00:00"
is an invalid date format in javascript. Noticenew Date("2016-22-08T15:04:36+00:00")
outputsInvalid Date