Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sort array according to the date property of the objects JavaScript
In JavaScript, sorting an array of objects by date requires converting date strings to Date objects for proper comparison. The Array.sort() method with a custom comparator function handles this efficiently.
Sample Data
Consider an array of objects with date properties:
const arr = [
{date: "2016-06-08 18:10:00"},
{date: "2016-04-26 20:01:00"},
{date: "2017-02-06 14:38:00"},
{date: "2017-01-18 17:30:21"},
{date: "2017-01-18 17:24:00"}
];
Using Array.sort() with Date Comparison
The most straightforward approach uses Array.sort() with a comparator function that converts strings to Date objects:
const arr = [
{date: "2016-06-08 18:10:00"},
{date: "2016-04-26 20:01:00"},
{date: "2017-02-06 14:38:00"},
{date: "2017-01-18 17:30:21"},
{date: "2017-01-18 17:24:00"}
];
const sortByDate = (arr = []) => {
arr.sort((a, b) => {
const dateA = new Date(a.date);
const dateB = new Date(b.date);
return dateA < dateB ? -1 : (dateA > dateB ? 1 : 0);
});
};
sortByDate(arr);
console.log(arr);
[
{ date: '2016-04-26 20:01:00' },
{ date: '2016-06-08 18:10:00' },
{ date: '2017-01-18 17:24:00' },
{ date: '2017-01-18 17:30:21' },
{ date: '2017-02-06 14:38:00' }
]
Simplified Version Using Subtraction
Since Date objects can be subtracted directly, we can simplify the comparator:
const arr2 = [
{date: "2016-06-08 18:10:00"},
{date: "2016-04-26 20:01:00"},
{date: "2017-02-06 14:38:00"}
];
arr2.sort((a, b) => new Date(a.date) - new Date(b.date));
console.log(arr2);
[
{ date: '2016-04-26 20:01:00' },
{ date: '2016-06-08 18:10:00' },
{ date: '2017-02-06 14:38:00' }
]
Sorting in Descending Order
To sort from newest to oldest, reverse the comparison:
const arr3 = [
{date: "2016-06-08 18:10:00"},
{date: "2016-04-26 20:01:00"},
{date: "2017-02-06 14:38:00"}
];
arr3.sort((a, b) => new Date(b.date) - new Date(a.date));
console.log(arr3);
[
{ date: '2017-02-06 14:38:00' },
{ date: '2016-06-08 18:10:00' },
{ date: '2016-04-26 20:01:00' }
]
How It Works
The sort() method uses a comparator function that returns:
- Negative value: first element comes before second
- Positive value: first element comes after second
- Zero: elements are equal
Converting date strings to Date objects enables proper chronological comparison, as string comparison would sort lexicographically rather than chronologically.
Conclusion
Use Array.sort() with Date object conversion for reliable date-based sorting. The subtraction method (new Date(a.date) - new Date(b.date)) provides the cleanest implementation for ascending order.
