Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 156 · Arrays

Sorting Arrays

Sort JavaScript arrays the right way. Learn why numbers sort wrong by default, how comparator functions work, toSorted, reverse and localeCompare.

Sorting looks like the simplest thing an array can do: put the items in order. In JavaScript it hides one famous trap. Call sort() on a list of numbers with no arguments and [10, 9, 1] becomes [1, 10, 9]. Once you understand why, sorting becomes one of the most flexible tools you have.

In this lesson you will learn how the default sort works, how to write comparator functions for numbers, strings, dates and objects, how to sort by several fields, and how to sort without changing the original array using toSorted().

The default sort compares strings

array.sort() with no arguments converts every item to a string and orders those strings by their UTF-16 code units. For words in one case, that looks fine. For numbers, it does not:

JS The default sort

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The scores come out as [100, 1000, 25, 3, 42] because the string "100" comes before "25" in the same way that "apple" comes before "banana": character by character. And every capital letter has a smaller code than every lowercase letter, so "Banana" sorts before "mango".

The default is only safe for strings that share one case and use plain English letters. For everything else, you pass a comparator.

Comparator functions

A comparator is a function that receives two items, usually called a and b, and returns a number that tells sort() how they relate:

Return value Meaning
Negative (e.g. -1) a goes before b
Positive (e.g. 1) a goes after b
0 Keep their current order

For numbers, subtracting does exactly this. If a is smaller, a - b is negative, so a goes first:

JavaScript
numbers.sort((a, b) => a - b); // ascending: 1, 2, 3
numbers.sort((a, b) => b - a); // descending: 3, 2, 1

Two more facts are important:

  • sort() changes the array in place and also returns that same array. It does not make a copy.
  • The sort is stable: items that compare as equal keep their original relative order. Every modern engine guarantees this, and you will rely on it later.
JS Sorting numbers with a comparator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The exact pairs the engine compares are an implementation detail, so do not depend on them. A comparator should only look at a and b and answer the same way every time it sees the same pair.

Return a number, not a boolean. (a, b) => a > b looks reasonable but returns true or false, which become 1 and 0. A comparator that never returns a negative number gives unreliable results that can differ between browsers.

Sorting strings properly with localeCompare

For text that people will read, compare strings with localeCompare(). It returns a negative number, zero or a positive number, which is exactly what a comparator needs, and it follows the rules of real languages instead of raw character codes:

JavaScript
names.sort((a, b) => a.localeCompare(b));

localeCompare() also takes a locale and options. Two options solve the most common problems:

  • sensitivity: "base" treats "a", "A" and "á" as equal, which is handy for case-insensitive sorting.
  • numeric: true compares digit runs as numbers, so "file10" comes after "file9". This is often called natural sort.
JS Human-friendly string sorting

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The [...cities] spread makes a copy first, so each line starts from the original order. You will learn a cleaner way to do that in a moment.

Sorting thousands of strings? Create one Intl.Collator and reuse its compare method: const collator = new Intl.Collator(undefined, { numeric: true }); list.sort(collator.compare);. It applies the same rules as localeCompare() but is faster in a loop. The Intl lesson covers it in detail.

Sorting objects by a property

Real data is usually an array of objects. The comparator simply reaches into each object for the value to compare:

JavaScript
products.sort((a, b) => a.price - b.price);              // by number
products.sort((a, b) => a.name.localeCompare(b.name));   // by string
events.sort((a, b) => a.date - b.date);                  // Date objects subtract as timestamps

Dates work with subtraction because a Date turns into its timestamp in milliseconds when you use -. If your dates are ISO strings such as "2026-03-14", localeCompare() sorts them correctly too, because that format puts the biggest unit first.

Sorting by several fields

To sort by one field and break ties with another, compare the first field and only fall back to the second when the result is 0. The || operator makes this short, because 0 is falsy:

JS Multi-key sorting

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the comparator from left to right: if the teams differ, that decides it; if they are the same, the points decide; if those match too, the names do.

toSorted(): sort without changing the original

Because sort() works in place, sorting an array you received from somewhere else can cause surprising bugs. Another part of your program may still expect the original order.

The newer toSorted() method takes the same optional comparator but returns a new, sorted array and leaves the original alone. It has siblings that follow the same pattern:

Changes the array Returns a new array
sort(compare) toSorted(compare)
reverse() toReversed()
splice(...) toSpliced(...)
arr[i] = value with(i, value)
JS toSorted and toReversed

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Support: toSorted(), toReversed(), toSpliced() and with() arrived in ES2023 and work in all current major browsers (Chrome and Edge 110+, Firefox 115+, Safari 16+) and in Node.js 20+. For older environments, copy first with [...array] or array.slice() and then call sort().

Reversing

reverse() flips the order of an array in place and returns it. It does not sort anything; it only reverses whatever order the items are in now. So array.sort().reverse() gives a descending order, but writing the comparator the other way round (b - a) does the same job in one step.

Use toReversed() when you want a reversed copy, as in the example above.

Shuffling: a sort you should not write

You may see this "shuffle" online:

JavaScript
// Don't do this
items.sort(() => Math.random() - 0.5);

It breaks the rule that a comparator must answer consistently, so the result is biased: some orders appear far more often than others. The correct tool is the Fisher–Yates shuffle, which walks backwards through the array and swaps each item with a random earlier one (or itself):

JavaScript
function shuffle(array) {
  const result = [...array];
  for (let i = result.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [result[i], result[j]] = [result[j], result[i]];
  }
  return result;
}

Every order is equally likely, and it runs in a single pass. The swap uses array destructuring, and the random index comes from the Math lesson.

A few more details

  • undefined always goes last. sort() moves undefined items to the end without ever passing them to your comparator. Empty slots in sparse arrays go after them.
  • NaN breaks number comparators. NaN - 5 is NaN, which the sort treats like 0, so the order around it becomes unpredictable. Clean or filter your data first.
  • Sorting is not free. It takes roughly n × log n comparisons. That is fast for thousands of items, but sort once rather than inside a loop, and keep comparators cheap.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What does [5, 40, 100].sort() return?

    With no comparator, the items are compared as strings. "100" comes before "40", which comes before "5", because the first characters are "1", "4" and "5".
  2. 2. Which comparator sorts an array of numbers from largest to smallest?

    When b is bigger, b - a is positive, so a moves after b. The boolean versions never return a negative number and give unreliable results.
  3. 3. You must not change an array called orders, but you need a copy sorted by total. Which line does that?

    toSorted() returns a new array. sort() and reverse() change orders in place, and assigning orders to another variable does not copy it.
  4. 4. Why does (a, b) => a.city.localeCompare(b.city) || a.name.localeCompare(b.name) sort by city and then by name?

    0 is falsy, so || moves on to the name comparison only when the cities are equal. Any non-zero city result is returned straight away.
  5. 5. Why is items.sort(() => Math.random() - 0.5) a bad shuffle?

    A comparator must give the same answer for the same pair. Random answers produce a biased result; use the Fisher–Yates shuffle instead.

Summary

  • sort() with no comparator compares items as strings, so numbers and mixed-case words sort wrongly.
  • A comparator returns a negative number (a first), a positive number (b first) or 0 (keep the order). Use a - b for ascending numbers and b - a for descending.
  • Use localeCompare() (or a reusable Intl.Collator) for human-readable text; numeric: true gives natural sort.
  • Chain comparisons with || to sort by several fields; the sort is stable, so equal items keep their order.
  • sort() and reverse() change the array in place. toSorted() and toReversed() return new arrays.
  • Shuffle with Fisher–Yates, never with a random comparator.

Next: Array Recipes — grouping, removing duplicates, flattening, chunking and more.