JavaScript Array toSorted()
Examples
const fruits = ["Banana", "Orange", "Apple", "Mango"];
// Sort the Array
const fruit2 = fruits.toSorted();
More Examples Blow !
Description
The toSorted()
method sorts the elements of an array in alphabetical order.
The toSorted()
method returns a new array.
The toSorted()
method does not overwrite the original array.
The toSorted()
method is the copying version of the
sort()
method.
Array Sort Methods:
Method | Finds |
---|---|
reverse() | Reverses the order of the elements in an array |
sort() | Sorts the elements of an array |
toReversed() | Reverses the elements of an array into a new array |
toSorted() | Sorts the elements of an array into a new array |
Sort Compare Function
Sorting alphabetically works well for strings ("Apple" comes before "Banana").
But, sorting numbers can produce incorrect results.
"25" is bigger than "100", because "2" is bigger than "1".
You can fix this by providing a "compare function" (See examples below).
Syntax
Parameters
A function that defines a sort order. The function should return a negative, zero, or positive value, depending on the arguments:
- function(a, b){return a-b}
When sort() compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.
Example:
The sort function will sort 40 as a value lower than 100.
When comparing 40 and 100, sort() calls the function(40,100).
The function calculates 40-100, and returns -60 (a negative value).
Return Value
More Examples
Sort Descending
Sort and then reverse the order:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
// Sort the Array
const fruits2 = fruits.toSorted();
// Reverse the Array
fruits2.reverse();
Numeric Sorts
Using a Sort Function
Sort numbers in ascending order:
const points = [40, 100, 1, 5, 25, 10];
// Sort the Array
let points2 = points.toSorted(function(a, b){return a-b});
Sort numbers in descending order:
const points = [40, 100, 1, 5, 25, 10];
// Sort the Array
let points2 = points.toSorted(function(a, b){return b-a});
Find the lowest value:
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in ascending order
let points2 = points.toSorted(function(a, b){return a-b});
let lowest = points2[0];
Find the highest value:
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in descending order:
let points2 = points.toSorted(function(a, b){return b-a});
let highest = points2[0];
Find the highest value:
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in ascending order:
let points2 = points.toSorted(function(a, b){return a-b});
let highest = points2[points.length-1];
Array Tutorials:
Browser Support
toSorted()
is a JavaScript 2023 feature.
ES 2023 is supported in all modern browsers since July 2023:
Chrome 110 |
Edge 110 |
Firefox 115 |
Safari 16.4 |
Opera 96 |
Feb 2023 | Feb 2023 | Jul 2023 | Mar 2023 | May 2023 |