In this article, we will explore the various techniques and approaches to JavaScript sorting by date, providing you with a guide to handle this task efficiently.
Knowing that in the world of web development, sorting data is a fundamental task.
Sorting data allows us to organize information in a meaningful way, making it easier for users to navigate and find what they’re looking for.
What is JavaScript?
JavaScript is a versatile programming language that is widely used for web development. It enables developers to create interactive and dynamic web pages, adding functionality and interactivity to the user experience.
Why Sort by Date?
Sorting data by date is crucial in many web applications, such as event calendars, blog posts, and e-commerce platforms. By sorting data chronologically, users can easily find the most recent or relevant information.
Before diving into the sorting techniques, let’s first understand how dates are represented in JavaScript.
Understanding Dates in JavaScript
In JavaScript, dates are stored as objects with the Date constructor.
These objects contain various methods and properties to manipulate and extract information from dates.
To create a new date object, you can use the following syntax:
const currentDate = new Date();This will create a new date object representing the current date and time.
Sorting an Array of Dates
Now that we have a basic understanding of dates in JavaScript, let’s explore how to sort an array of dates.
const dates = [
new Date('2022-01-15'),
new Date('2022-05-20'),
new Date('2021-12-01'),
new Date('2022-03-10'),
];
dates.sort((a, b) => a - b);
In the example above, we have an array of dates. By calling the sort method on the array and passing a comparison function as an argument, we can sort the dates in ascending order.
The comparison function (a, b) => a – b compares two dates and returns a negative value if a should be sorted before b, a positive value if a should be sorted after b, or 0 if they are equal.
Sorting an Array of Objects by Date
In real-world scenarios, you often encounter arrays of objects that contain date properties. To sort such arrays based on the date property, we can modify the previous approach.
Let’s assume we have an array of events, where each event has a date property:
const events = [
{ name: 'Event 1', date: new Date('2022-01-15') },
{ name: 'Event 2', date: new Date('2022-05-20') },
{ name: 'Event 3', date: new Date('2021-12-01') },
{ name: 'Event 4', date: new Date('2022-03-10') },
];
To sort the array of events by the date property, we can modify the comparison function:
events.sort((a, b) => a.date - b.date);By comparing the date properties of the objects, the array will be sorted in ascending order based on the dates.
Sorting in Descending Order
By default, the sort method sorts arrays in ascending order. However, there may be cases where you need to sort dates in descending order. To achieve this, we can reverse the sorted array:
dates.sort((a, b) => b - a);Similarly, for sorting arrays of objects:
events.sort((a, b) => b.date - a.date);By reversing the comparison logic, we can obtain a descending-order sort.
Anyway here are some of the functions you might want to learn and can help you:
Sort an Array of Date Objects (Quick Reference)
const dates = [
new Date("2026-01-15"),
new Date("2025-11-20"),
new Date("2026-03-05"),
];
// Ascending (oldest first)
dates.sort((a, b) => a - b);
// Descending (newest first)
dates.sort((a, b) => b - a);JavaScript subtracts Date objects by converting them to milliseconds (Unix timestamps). The result is a positive or negative number, which is exactly what sort() expects as a comparator return value.
Sort Objects by a Date Property
const orders = [
{ id: 1, orderedAt: "2026-05-12T10:30:00Z" },
{ id: 2, orderedAt: "2026-05-10T14:15:00Z" },
{ id: 3, orderedAt: "2026-05-11T09:00:00Z" },
];
// Sort newest first
orders.sort((a, b) =>
new Date(b.orderedAt) - new Date(a.orderedAt)
);
console.log(orders);
// Output: 1 (May 12), 3 (May 11), 2 (May 10)The new Date(string) step is necessary because the comparison is between Date objects, not raw ISO strings. ISO 8601 strings do sort correctly as plain strings, but for any other format (like “5/12/2026”) you must convert.
Sort by Multiple Keys (Date Then Name)
const events = [
{ name: "Quiz", date: "2026-05-12" },
{ name: "Exam", date: "2026-05-12" },
{ name: "Class", date: "2026-05-15" },
{ name: "Lab", date: "2026-05-10" },
];
events.sort((a, b) => {
const d = new Date(a.date) - new Date(b.date);
if (d !== 0) return d; // primary: date
return a.name.localeCompare(b.name); // tiebreaker: name
});This pattern is used for BSIT capstone “events by date” pages where multiple items share the same date. The localeCompare() handles international characters correctly — better than simple < / > comparison for strings with accents.
Handling Invalid Dates Safely
const records = [
{ id: 1, date: "2026-05-12" },
{ id: 2, date: "" }, // empty
{ id: 3, date: "not-a-date" }, // garbage
{ id: 4, date: "2026-05-10" },
];
records.sort((a, b) => {
const da = new Date(a.date);
const db = new Date(b.date);
const aValid = !isNaN(da);
const bValid = !isNaN(db);
if (aValid && !bValid) return -1; // valid first
if (!aValid && bValid) return 1;
if (!aValid && !bValid) return 0;
return da - db;
});Without the isNaN() check, invalid Date objects produce NaN when subtracted, and NaN never returns positive or negative — so the sort silently breaks. Always validate user-supplied dates before sorting.
Common Sort-by-Date Mistakes
- Sorting raw date strings as text without ISO format.
"5/12/2026" < "5/10/2026"is true alphabetically. Convert to Date first or use ISO format (which IS sortable as text). - Forgetting that sort() MUTATES the array. If you need to keep the original order, clone first:
[...arr].sort(...). - Returning true/false from the comparator.
(a, b) => a > breturns true/false; sort needs a NUMBER (negative/zero/positive). Use subtraction or explicit conditionals. - Handling NaN incorrectly. When a Date string is invalid,
new Date(s)creates an Invalid Date. Subtracting Invalid Dates produces NaN, which silently breaks sort. Validate before sorting. - Timezone surprises.
"2026-05-12"is interpreted as UTC midnight. In a +08:00 timezone (Philippines), that displays as 8 AM on May 12. Mixing date-only and datetime strings can cause off-by-one-day bugs.
Conclusion
In this comprehensive guide, we have explored the techniques and approaches to sort data by date in JavaScript.
Sorting data is a crucial task in web development, and by leveraging the power of JavaScript’s sort method, you can efficiently organize and present information to users.
Whether you’re working with arrays of dates or objects with date properties, the provided examples and explanations should equip you with the necessary knowledge to tackle any sorting challenge.
That concludes our discussion on this topic. We hope that you have gained valuable insights from this article.
Stay tuned for more & Happy coding!😊
Frequently Asked Questions
How do I sort an array by date in JavaScript?
For an array of Date objects: dates.sort((a, b) => a - b) sorts ascending; dates.sort((a, b) => b - a) sorts descending. For objects with a date property as a string: arr.sort((a, b) => new Date(a.date) - new Date(b.date)). JavaScript converts Date subtraction to milliseconds, which the sort comparator uses correctly.
How do I sort by date string in YYYY-MM-DD format without converting to Date?
ISO 8601 date strings (YYYY-MM-DD) sort correctly as plain text because the format is left-justified by significance. arr.sort((a, b) => a.date.localeCompare(b.date)) works for ISO strings. For any other format like “5/12/2026” you must convert to Date first — the alphabetical sort would give wrong results.
Does sort() modify the original array in JavaScript?
Yes — sort() MUTATES the original array. If you need to keep the original order, clone first: const sorted = [...arr].sort(...) or use the newer arr.toSorted(...) method (Node 20+, modern browsers) which returns a new sorted array without mutation.
How do I sort dates in descending order (newest first)?
Subtract in reverse order: arr.sort((a, b) => b - a) for Date objects, or arr.sort((a, b) => new Date(b.date) - new Date(a.date)) for objects. Putting b first reverses the comparison. The result puts the most recent date at index 0.
What happens if my array has invalid date strings?
Invalid Dates produce NaN when subtracted, which silently breaks the sort — the comparator never returns positive or negative, so elements stay in undefined order. Always validate with !isNaN(new Date(s)) before subtracting, and decide whether invalid dates go first, last, or are filtered out before sorting.
