Use JavaScript’s Array.prototype.sort method to Sort an array of objects by a date field. Just create Date
objects from your date strings before you can compare them.
array.sort(function(a,b){
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(b.date) - new Date(a.date);
});
Sort array of objects JavaScript by date
Simple example code uses the new Date()
constructor to change them to javascript date
objects.
<!DOCTYPE html>
<html>
<body>
<script>
var myArray = [{
name: "Joe Tim",
date: "Mon Oct 31 2021 00:00:00 GMT-0700 (PDT)"
}, {
name: "Sam Steve",
date: "Sun Oct 30 2021 00:00:00 GMT-0700 (PDT)"
}, {
name: "John Smith",
date: "Sat Oct 29 2021 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);
</script>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this JS sort array.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version