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
Selected Reading
How to sort date array in JavaScript
Sorting arrays of dates is a common task in JavaScript. This tutorial shows how to sort an array containing date strings in ascending chronological order.
Suppose we have an array that contains some dates like this:
const arr = [
[ '02/13/2015', 0.096 ],
[ '11/15/2013', 0.189 ],
[ '05/15/2014', 0.11 ],
[ '12/13/2013', 0.1285 ],
[ '01/15/2013', 0.12 ],
[ '01/15/2014', 0.11 ],
[ '02/14/2014', 0.11 ],
[ '03/14/2014', 0.11 ]
];
console.log("Original array:");
console.log(arr.slice(0, 4)); // Show first 4 items
Original array: [ [ '02/13/2015', 0.096 ], [ '11/15/2013', 0.189 ], [ '05/15/2014', 0.11 ], [ '12/13/2013', 0.1285 ] ]
We need to sort this array in ascending order according to the dates in each sub-array.
Using Array.sort() with Date Comparison
The Array.sort() method with a custom comparator function can sort dates by converting them to Date objects:
const arr = [
[ '02/13/2015', 0.096 ],
[ '11/15/2013', 0.189 ],
[ '05/15/2014', 0.11 ],
[ '12/13/2013', 0.1285 ],
[ '01/15/2013', 0.12 ],
[ '01/15/2014', 0.11 ],
[ '02/14/2014', 0.11 ],
[ '03/14/2014', 0.11 ]
];
const sortByDate = arr => {
const sorter = (a, b) => {
return new Date(a[0]) - new Date(b[0]);
};
arr.sort(sorter);
};
sortByDate(arr);
console.log("Sorted array:");
console.log(arr);
Sorted array: [ [ '01/15/2013', 0.12 ], [ '11/15/2013', 0.189 ], [ '12/13/2013', 0.1285 ], [ '01/15/2014', 0.11 ], [ '02/14/2014', 0.11 ], [ '03/14/2014', 0.11 ], [ '05/15/2014', 0.11 ], [ '02/13/2015', 0.096 ] ]
How It Works
The sorting function works by:
-
Date Conversion:
new Date(a[0])converts the string to a Date object - Numeric Subtraction: Subtracting Date objects returns milliseconds difference
- Comparison: Negative result means first date is earlier, positive means later
Alternative: One-liner Approach
You can also write this more concisely:
const dates = [
[ '12/25/2023', 'Christmas' ],
[ '01/01/2023', 'New Year' ],
[ '07/04/2023', 'Independence Day' ]
];
const sorted = dates.sort((a, b) => new Date(a[0]) - new Date(b[0]));
console.log(sorted);
[ [ '01/01/2023', 'New Year' ], [ '07/04/2023', 'Independence Day' ], [ '12/25/2023', 'Christmas' ] ]
Key Points
-
Array.sort()modifies the original array - Date strings must be in a format recognizable by the Date constructor
- For descending order, reverse the subtraction:
new Date(b[0]) - new Date(a[0])
Conclusion
Sorting date arrays in JavaScript is straightforward using Array.sort() with Date object comparison. The key is converting date strings to Date objects for proper chronological sorting.
Advertisements
