← All concepts
Working With Arrays

Sorting Arrays

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

Loading visual…

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.

Where you see this

Practice this

Further reading