Sort array of objects with date field by date
Here's a solution using standard Javascript by converting both values to date object and comparing their value.
myArray.sort((d1, d2) => new Date(d1.date).getTime() - new Date(d2.date).getTime());
A complete snippet:
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((d1, d2) => new Date(d1.date).getTime() - new Date(d2.date).getTime());
console.log(myArray);
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);
Your date values are strings, so you need to use the new Date()
constructor to change them to javascript date
objects. This way you can sort them (using _.sortBy
).
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 = _.sortBy(myArray, function(dateObj) {
return new Date(dateObj.date);
});
console.log(myArray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>