JavaScriptArrays

Array.prototype.sort()

Sorts the array’s elements in place and returns the same array.

Returns
The same, sorted array.
Changes the original
Yes
On this page

Example

#
JavaScript
const numbers = [10, 9, 1, 25]

console.log([...numbers].sort())
console.log([...numbers].sort((a, b) => a - b))
console.log([...numbers].sort((a, b) => b - a))
Console
[1, 10, 25, 9]
[1, 9, 10, 25]
[25, 10, 9, 1]

Definition and usage

#

The sort() method arranges the array’s elements according to the comparator function you give it. It changes the original and returns a reference to that same array.

Without a comparator, elements are converted to strings and sorted alphabetically by character code. That’s why [10, 9, 1].sort() gives [1, 10, 9]. Always sort numbers with the function (a, b) => a - b.

The comparator returns a negative number when a should come before b, a positive one when it should come after, and zero when the order doesn’t matter. For strings with accented characters, use localeCompare().

Syntax

#
Syntax
array.sort()
array.sort(compareFn)

Parameters

#
  • compareFn

    function (a, b)

    The comparator function. A negative result places a before b.

More examples

#
Sorting objects and localized strings
JavaScript
const students = [
  { name: 'Zoe', points: 90 },
  { name: 'Amy', points: 120 },
  { name: 'Noah', points: 90 }
]

const byName = [...students].sort((a, b) => a.name.localeCompare(b.name, 'en'))
console.log(byName.map((s) => s.name))
Console
['Amy', 'Noah', 'Zoe']

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Always sort numbers with the function (a, b) => a - b. The default sort treats them as text.
  • If you don’t want to change the original, use toSorted() or sort a copy: [...array].

Related entries

#

Spotted a mistake or missing an example? Write to us.