Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.prototype.sort

Sorts the elements of an array.

Available since: ES1

Syntax

array.sort(compareFn)

Parameters

ParameterTypeDescription
compareFnFunctionOptional. A function comparing two elements: a negative number puts the first one earlier, a positive number later.

Return value

ArrayThe same array, sorted in place.

Examples

Sorting strings:

console.log(['pear', 'apple', 'plum'].sort().join(', '));

Output:

apple, pear, plum

Without a comparison function numbers are sorted as strings:

console.log([10, 9, 1].sort().join(', '));
console.log([10, 9, 1].sort((a, b) => a - b).join(', '));

Output:

1, 10, 9
1, 9, 10

Notes

The method modifies the array itself. To keep the original order, sort a copy: [...array].sort().

See also

Related recipes

In the tutorial

  • Sorting arrays — How to sort an array in JavaScript: sort, the compare function, sorting numbers, strings and objects, reverse and toSorted.

Thanks for reading!

Donate to the site — we work hard for you.