1. javascript
  2. /array methods
  3. /sort

sort() Array Method

The sort() array method is a built-in method in JavaScript that modifies the original array and sorts its elements in place.

Here is a quick example:

let fruits = ['apple', 'banana', 'kiwi', 'mango'];

fruits.sort();

console.log(fruits); 
// Output: ['apple', 'banana', 'kiwi', 'mango']

By default, the sort() method sorts the elements alphabetically in ascending order.

To reverse the sort order, you can use the reverse() method after calling the sort() method.

Syntax and Parameters

array.sort([compareFunction])
ParameterDescriptionOptional/Required
compareFunctionA function that defines the sort order. If omitted, the elements are sorted in ascending order according to their converted values. The function should take two arguments and return a negative, positive, or zero value.Optional

sort() method examples:

Sort an array in ascending order

let numbers = [3, 1, 2];

numbers.sort((a, b) => a - b);
console.log(numbers);
// Output: [1, 2, 3]

Sort an array in ascending order by age

let people = [{ name: 'Alice', age: 30 }, { name: 'Bob', age: 25 }, { name: 'Eve', age: 35 }];

people.sort((a, b) => a.age - b.age);
console.log(people);
// Output: [{ name: 'Bob', age: 25 }, { name: 'Alice', age: 30 }, { name: 'Eve', age: 35 }]

Sort an array in descending order by name

let people = [{ name: 'Alice', age: 30 }, { name: 'Bob', age: 25 }, { name: 'Eve', age: 35 }];

people.sort((a, b) => b.name.localeCompare(a.name));
console.log(people);
// Output: [{ name: 'Eve', age: 35 }, { name: 'Alice', age: 30 }, { name: 'Bob', age: 25 }]

Other array sort methods that you may want to investigate include:

reverse() - Reverses the elements of an array in place.

sortBy() - Sorts the elements of an array in place according to the values returned by a mapping function.

orderBy() - Sorts the elements of an array in place according to the values returned by a key function.

How do you sort an array of JavaScript variables by one of its string property values?