Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk3 min

How to Sort an Array by Date in TypeScript

Sort dates in TypeScript with a timestamp comparator, choose ascending or descending order, and decide how to handle mutation, strings, invalid dates and ties.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a comparator that subtracts date timestamps. For an array of objects with Date values, this sorts oldest first without changing the original array:

interface Event {
  title: string;
  date: Date;
}

const ascending = [...events].sort(
  (a, b) => a.date.getTime() - b.date.getTime(),
);

const descending = [...events].sort(
  (a, b) => b.date.getTime() - a.date.getTime(),
);

Use the ascending comparator for oldest first and the descending one for newest first. The spread copies the array before JavaScript’s in-place sort() runs.

Sort Date objects by timestamp

A JavaScript Date represents a timestamp in milliseconds since the Unix epoch. Calling getTime() on two dates and subtracting the results gives the numeric comparison sort() needs. The same pattern works for a plain array of dates:

const dates: Date[] = [new Date("2025-04-10"), new Date("2023-08-01")];

const oldestFirst = [...dates].sort(
  (a, b) => a.getTime() - b.getTime(),
);

A negative comparator result places the first item before the second; a positive result places it after. A zero result means the comparator considers them equal. Avoid the default sort() with no comparator: it converts values to strings and sorts their text, which is not chronological date ordering. See MDN’s Array.prototype.sort() reference and MDN’s Date reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose whether to mutate the input

Array.prototype.sort() changes the array it is called on and returns that same array. In the examples, [...events] makes a shallow copy first, so the original array order stays intact. The objects inside the copied array are still shared; sorting does not clone or alter their date values.

  • Keep the original array order: use [...events].sort(compareDates).
  • Sort the existing array in place: use events.sort(compareDates) when changing its order is intended.
  • Use toSorted(): MDN documents this non-mutating alternative, but check that the project’s runtime and TypeScript library target support it before relying on it.

Handle date strings as input data

If dates arrive as strings, first establish their format and what their time zone means. The standard date-time string format is the portable choice; parsing other human-readable formats can be implementation-specific, and some strings are interpreted in local time. For values representing instants, use UTC (Z) or an explicit offset. See MDN’s Date() constructor reference.

Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem

For example, validate and parse strings before sorting. This version rejects an invalid value when it is encountered:

function timestamp(value: string): number {
  const result = Date.parse(value);
  if (Number.isNaN(result)) {
    throw new Error(`Invalid date: ${value}`);
  }
  return result;
}

const sorted = [...rows].sort(
  (a, b) => timestamp(a.date) - timestamp(b.date),
);

For repeated comparisons, parse each string once when data enters the application and store its timestamp, rather than parsing inside the comparator. This avoids repeating work during sorting; it is an implementation recommendation, not a benchmark claim.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If a value represents a calendar day rather than a precise instant, decide how calendar-day ordering should work before converting it to a timestamp. Turning local dates into instants without an explicit rule can make the displayed day shift across time zones.

Define what happens to invalid dates and ties

An invalid Date has a NaN timestamp. Subtracting that value does not produce a normal chronological comparison, so validate dates before sorting and choose a policy: reject them, filter them out, or explicitly place them last. Calling toISOString() on an invalid date throws a RangeError; see MDN’s invalid-date error reference.

JavaScript sorting is stable in ECMAScript 2019 and later: items the comparator considers equal retain their original relative order. If equal timestamps need a secondary order, add a tie-breaker, such as an ID or title. Comparators should be consistent and return a three-way result; a boolean comparator such as (a, b) => a.date > b.date does not express before, after, and equal correctly and can lead to engine-dependent results.

const sortedByDateThenTitle = [...events].sort((a, b) => {
  const byDate = a.date.getTime() - b.date.getTime();
  return byDate || a.title.localeCompare(b.title);
});

Which version should you use?

Situation Operation What to know
Plain Date[], oldest first dates.sort((a, b) => a.getTime() - b.getTime()) Mutates dates.
Objects with dates, newest first items.sort((a, b) => b.date.getTime() - a.date.getTime()) Reverse the subtraction to reverse the order.
Preserve the source array [...items].sort(compareDates) Copies the array, not the objects inside it.
String dates Validate and parse, then compare timestamps Use a known format and an explicit time-zone policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What TypeScript changes—and what it does not

The ordering behavior comes from JavaScript’s built-in Array.prototype.sort() and Date; TypeScript adds static type checking. Comparing getTime() results makes the numeric operation explicit and avoids relying on arithmetic directly between Date objects. For a basic coding example, no extra date-sorting library is needed.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.