Skip to main content

sort() in an array

The sort() method in JavaScript is used to sort the elements of an array. It mutates the original array (unlike most other methods) and can work with both numbers and strings if you provide a compare function.


Syntax

javascript
array.sort(compareFunction);

Where compareFunction is a callback of the form:

javascript
(a, b) => { // return a negative value if a should come before b // return a positive value if a should come after b // return 0 if the order doesn't matter }

Example 1. Simple string sorting

javascript
const fruits = ['banana', 'apple', 'cherry']; fruits.sort(); console.log(fruits); // ['apple', 'banana', 'cherry']

By default sort() sorts elements as Unicode strings, even if they are numbers! That's why numbers without a callback are sorted not by magnitude, but by character.


Example 2. A mistake when sorting numbers without a compare function

javascript
const numbers = [1, 10, 2, 5]; numbers.sort(); console.log(numbers); // [1, 10, 2, 5] - sorted as strings!

Fixed:

javascript
numbers.sort((a, b) => a - b); console.log(numbers); // [1, 2, 5, 10]

The function (a, b) => a - b sorts in ascending order, (a, b) => b - a - in descending order.


Example 3. Sorting by an object property

javascript
const users = [ { name: 'Tim', age: 25 }, { name: 'Alex', age: 30 }, { name: 'John', age: 20 } ]; users.sort((a, b) => a.age - b.age); console.log(users); // [ // { name: 'John', age: 20 }, // { name: 'Tim', age: 25 }, // { name: 'Alex', age: 30 } // ]

A common scenario is sorting an array of objects by a numeric field.


Example 4. Sorting strings alphabetically (case-insensitive)

javascript
const names = ['tim', 'Alex', 'john']; names.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' })); console.log(names); // ['Alex', 'john', 'tim']

localeCompare is the correct way to sort strings taking language and case into account.


Example 5. Sorting in descending order

javascript
const prices = [100, 500, 200, 50]; prices.sort((a, b) => b - a); console.log(prices); // [500, 200, 100, 50]

Important: sort() mutates the original array

javascript
const arr = [3, 1, 2]; const sorted = arr.sort(); console.log(sorted); // [1, 2, 3] console.log(arr); // [1, 2, 3] - the same array, mutated!

If you need to keep the original array, copy it before sorting:

javascript
const sortedCopy = [...arr].sort((a, b) => a - b);

Example 6. Sorting by multiple criteria

javascript
const users = [ { name: 'Tim', age: 25 }, { name: 'Alex', age: 25 }, { name: 'John', age: 20 } ]; users.sort((a, b) => { if (a.age !== b.age) return a.age - b.age; return a.name.localeCompare(b.name); }); console.log(users); // [ // { name: 'John', age: 20 }, // { name: 'Alex', age: 25 }, // { name: 'Tim', age: 25 } // ]

If the age is the same, sorting falls back to the name.


Mistakes to watch for

  1. Without a callback, strings are sorted instead of numbers
javascript
[10, 2, 1].sort(); // ['1', '10', '2']

Solution:

javascript
[10, 2, 1].sort((a, b) => a - b); // [1, 2, 10]
  1. Mutating the original array
javascript
const a = [3, 1, 2]; const b = a.sort(); console.log(a === b); // true - it's the same object
  1. Lack of stability in older JS versions

Sorting could be unstable in older engines (before ES2019). In modern ECMAScript versions sort() is stable - elements with equal order keep their original relative position.


When to use sort()

GoalIs sort() suitable?
Sort numbers or stringsYes
Sort objects by a fieldYes
Get a new sorted array without changing the originalYes, but only with a copy ([...arr])
Check a conditionNo
Transform dataNo

In short:

sort() sorts the elements of an array in place, by default as strings. To sort numbers, provide a compare function.

Memorization formula: arr.sort((a, b) => a - b) -> ascending arr.sort((a, b) => b - a) -> descending


Comparison with other methods

MethodReturns a new arrayMutates the originalPurpose
map()yesnoTransforms elements
filter()yesnoSelects elements
find()no (an element)noFinds the first matching element
reduce()no (a single value)noReduces to a single result
sort()no (the same array)yesSorts elements

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.