← All concepts
Working With Arrays

Sorting Arrays

Array.prototype.sort reorders elements in place, using a comparator's sign to decide each swap.

Definition

sort reorders the elements of an array in place and returns the same array reference, it does not make a copy. Called with no arguments, it converts every element to a string and sorts those strings in Unicode code point order, which is why the numbers 10 and 2 end up as [10, 2] instead of [2, 10], the character "1" simply sorts before "2". A comparator function, passed as sort's argument, controls the order directly: for two elements a and b, returning a negative number means a should come before b, returning a positive number means b should come before a, and returning 0 leaves their relative order unchanged (this has been guaranteed stable since ES2019). The idiomatic comparator for ascending numbers is (a, b) => a - b: when a is bigger than b the subtraction is positive, so b moves first, when a is smaller the subtraction is negative, so a stays first. Flipping it to (a, b) => b - a sorts descending instead. Because sort mutates, copying the array first with [...arr] or arr.slice() before sorting keeps the original untouched.

Examples

[10, 1, 2].sort();
// [1, 10, 2]

With no comparator, sort converts each value to a string, so "10" sorts before "2" alphabetically instead of numerically.

[10, 1, 2].sort((a, b) => a - b);
// [1, 2, 10]

A negative a - b keeps a first, a positive one swaps the pair, giving the correct ascending numeric order.

const nums = [3, 1, 2];
const sorted = [...nums].sort((a, b) => a - b);
// sorted is [1, 2, 3], nums is still [3, 1, 2]

Spreading into a new array before calling sort avoids mutating the original nums array, since sort would otherwise reorder it in place.

Common mistakes

  • Calling sort() with no comparator on numbers and expecting numeric order; it sorts them as strings by default.
  • Forgetting that sort mutates the original array in place, which can silently break code that expected the original order to stay unchanged.
  • Writing a comparator that returns a boolean instead of a number; sort needs a negative, zero, or positive number to decide order.

Key takeaways

  • sort mutates the array in place and, with no comparator, sorts elements as strings.
  • (a, b) => a - b sorts numbers ascending; (a, b) => b - a sorts descending.
  • Copy the array first with [...arr] or arr.slice() before sorting if the original order needs to be preserved.
Check your understanding

What does [10, 1, 2].sort() return, with no comparator?

Where you see this

  • Sorting a table's rows by whichever column the user clicks to sort on.
  • Ranking a leaderboard of scores from highest to lowest.
  • Ordering a list of dates or timestamps chronologically.
  • Alphabetizing names or labels correctly with localeCompare instead of the default string sort.

Practice this

Further reading

Previous
map, filter, and reduce
Next
Array Search Methods