0

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
3
  • Since you have ISO dates, it's safe to compare them as strings, use date1.localeCompare(date2) in your sort callback. Commented Jan 27, 2016 at 14:15
  • ^ arr.sort((a,b) => a.date.localeCompare(b.date)) Commented Jan 27, 2016 at 14:17
  • @sanjaypoyzer, unless it's a mistake in the formatting, "2016-22-08T15:04:36+00:00" is an invalid date format in javascript. Notice new Date("2016-22-08T15:04:36+00:00") outputs Invalid Date Commented Jan 27, 2016 at 14:23

1 Answer 1

3

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

@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.
You have to return -1, 0, or 1 from the sort callback, not true/false.
@georg Thanks, what do the -1, 0, or 1 values correspond to?
@sanjaypoyzer I guess less than, equal and greater than.
@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/…

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.