October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

How to Sort an Array of Objects by Property in TypeScript

Use a comparator with sort() to order objects by a property in TypeScript, and choose toSorted() or a copied array when the original must stay unchanged.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use JavaScript’s Array.prototype.sort() with a comparator that reads the property you want to order by. For numbers, subtract the values; for strings, compare them with localeCompare(). Note that sort() changes the original array.

Sort by a numeric property

For ascending order, return the difference between the corresponding properties:

As an Amazon Associate I earn from qualifying purchases.

type Item = { name: string; score: number };

const items: Item[] = [
  { name: "Ada", score: 9 },
  { name: "Lin", score: 4 },
];

items.sort((a, b) => a.score - b.score);

The comparator’s sign determines the order: a negative result puts a before b, a positive result puts it after, and zero treats them as equal. For descending order, reverse the operands:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
items.sort((a, b) => b.score - a.score);

This subtraction pattern is appropriate for valid numeric values. If a property might be NaN or missing, define how those cases should be ordered rather than relying on subtraction.

Sort by a string property

Use localeCompare() to compare string fields:

items.sort((a, b) => a.name.localeCompare(b.name));

For user-facing text, choose locale-aware behavior to suit the application’s language and data; there is no single locale policy that fits every use case.

Choose whether to change the original array

sort() rearranges the array in place and returns the same array reference. If you need to keep the original ordering, use toSorted() where both the runtime and TypeScript library definitions support it:

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
const sorted = items.toSorted((a, b) => a.score - b.score);

For broader compatibility, copy the array before sorting:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const sorted = [...items].sort((a, b) => a.score - b.score);

This is a shallow copy: the new array has a different ordering, but its elements are references to the same objects.

Common pitfalls and edge cases

  • Do not rely on the default order for numbers. Without a comparator, sort() converts values to strings, so numeric values can be ordered lexically rather than numerically.
  • Handle optional properties deliberately. If a key has a type such as string | undefined, decide where missing values belong before writing the comparison. A generic helper should constrain its selected key to comparable values and account for such unions.
  • Keep the comparator consistent. Return zero when the selected values compare equal. Modern sort() is stable, so equal elements retain their relative order. A comparator that returns only zero and one sign does not express a valid, consistent ordering.
  • Avoid side effects. The comparator should give consistent results and should not mutate the objects it compares.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose the comparator for your data

Property and goal Comparator Notes
Valid numbers, ascending (a, b) => a.value - b.value Pass a comparator to get numeric rather than default string-based ordering.
Valid numbers, descending (a, b) => b.value - a.value Reverse the operands.
Strings (a, b) => a.name.localeCompare(b.name) For human-readable text, choose the locale behavior deliberately.
Keep the input unchanged toSorted() or [...items].sort() toSorted() requires runtime and TypeScript library support; copying first is an alternative.

See MDN’s Array.prototype.sort reference for the method’s comparator behavior and additional examples.

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
PC Slower Than It Used to Be?Free scan - under a minute

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.