Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of objects with date field by date

Give the following array of objects, I need to sort them by the date field ascending.

var myArray = [   {     name: "Joe Blow",     date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"   },   {     name: "Sam Snead",     date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"   },   {     name: "John Smith",     date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"     } ]; 

so that in this example, the final result would be John Smith, Sam Snead, and Joe Blow.

I am trying to use lodash's _.sortBy(), but I can't get any sorting to take place no matter how I try to use it:

_.sortBy(myArray, function(dateObj) {   return dateObj.date; }); 

or

_.sortBy(myArray, 'date'); 

What do I need to change to get my array sorted properly? I also have Moment.js, so I can use it to format the date string if needed. I tried converting the date property using .unix(), but that didn't make a difference.

Thanks.

like image 333
wonder95 Avatar asked Dec 05 '16 01:12

wonder95


People also ask

How do I sort dates in TypeScript?

To sort an array of objects by date in TypeScript: Call the sort() method on the array, passing it a function. The function will be called with 2 objects from the array. Subtract the timestamp of the date in the second object from the timestamp of the date in the first.


1 Answers

You don't really need lodash. You can use JavaScript's Array.prototype.sort method.

You'll need to create Date objects from your date strings before you can compare them.

var myArray = [{    name: "Joe Blow",    date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"  }, {    name: "Sam Snead",    date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"  }, {    name: "John Smith",    date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"  }];    myArray.sort(function compare(a, b) {    var dateA = new Date(a.date);    var dateB = new Date(b.date);    return dateA - dateB;  });    console.log(myArray);
like image 95
Punit Avatar answered Oct 07 '22 08:10

Punit