DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk2 min

How to Sort a Number Array in Descending Order in TypeScript

Sort numbers descending in TypeScript with (a, b) => b - a. Learn when to use mutating sort() or non-mutating toSorted().
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a numeric comparator with sort(): numbers.sort((a, b) => b - a). This puts larger numbers before smaller ones, but changes the original array. If you need to keep the original order, use toSorted() instead, provided your runtime supports it.

Sort the array in place with sort()

For an array typed as number[], pass a comparator that subtracts the first value from the second in reverse order:

As an Amazon Associate I earn from qualifying purchases.

const numbers: number[] = [10, 3, 25, 7];
const descending = numbers.sort((a, b) => b - a);

console.log(descending); // [25, 10, 7, 3]

The comparator returns a negative value when its first argument should come before its second, a positive value when it should come after, and zero when they compare equal. With (a, b) => b - a, larger values are placed first. For ascending order, reverse the subtraction: (a, b) => a - b. See MDN’s Array.prototype.sort() reference.

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.

sort() mutates the array and returns the same array reference, now sorted. Use it when changing the original array is intended:

const scores: number[] = [12, 40, 7, 40];
scores.sort((a, b) => b - a);

console.log(scores); // [40, 40, 12, 7]

Keep the original array unchanged with toSorted()

toSorted() applies the same comparator but returns a new sorted array:

const scores: number[] = [12, 40, 7, 40];
const sortedScores = scores.toSorted((a, b) => b - a);

console.log(sortedScores); // [40, 40, 12, 7]
console.log(scores);       // [12, 40, 7, 40]

MDN documents toSorted() as the non-mutating alternative. Check that the JavaScript runtime where your code runs supports it. If TypeScript does not recognize the method, check the project’s configured TypeScript lib target; changing type declarations alone does not add runtime support.

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

Why plain sort() does not sort numbers numerically

Without a comparator, JavaScript sorts elements by comparing their string conversions. That can produce an order that looks lexicographic rather than numeric: MDN gives [1, 30, 4, 21, 100000] as an example that sorts by default to [1, 100000, 21, 30, 4]. For numeric order, always provide a numeric comparator such as (a, b) => b - a.

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

Handle ties, invalid numbers, and string input

Equal values

For finite numbers, equal values make the subtraction comparator return zero. JavaScript’s array sort is stable, so elements that compare equal retain their relative order.

NaN values

If an array may contain NaN, subtraction can itself return NaN, so the simple comparator may not express the ordering you want. Decide where NaN belongs and handle it explicitly in the comparator rather than assuming ordinary numeric subtraction covers it.

Values arriving as strings

These examples assume the array contains numbers. If values arrive as strings, validate and convert them before sorting; a comparator intended for numeric values does not guarantee the intended result for unvalidated input.

Keep the comparator consistent

A comparator should be pure and give consistent results for repeated pairs; its ordering should also be reflexive, antisymmetric, and transitive. These rules help the sort produce a predictable order.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

TypeScript uses JavaScript’s sorting behavior

There is no TypeScript-specific sorting API or package needed for this task. TypeScript preserves JavaScript’s runtime behavior, so the same array methods and comparator work in TypeScript as in JavaScript. The relevant distinction is whether you want to mutate the existing array with sort() or create a sorted copy with toSorted().

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 *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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
Crashes, No Sound, or Screen Glitches?Free driver scan
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.