// Create an Array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
// Sort the Array
const fruit2 = fruits.toSorted();
Try it Yourself »More Examples Blow !
DescriptionThe 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.
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).
Syntaxarray.sort(compareFunction)
Parameters Parameter Description compareFunction Optional.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 Type Description Array A new array with the items sorted. More Examples Sort DescendingSort and then reverse the order:
// Create an Array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
// Sort the Array
const fruits2 = fruits.toSorted();
// Reverse the Array
fruits2.reverse();
Try it Yourself » Numeric Sorts Using a Sort FunctionSort numbers in ascending order:
// Create an Array
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:
// Create an Array
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:
// Create an Array
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];
Try it Yourself »Find the highest value:
// Create an Array
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];
Try it Yourself »Find the highest value:
// Create an Array
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];
Try it Yourself » Browser SupporttoSorted()
is a JavaScript 2023 feature.
ES 2023 is supported in all modern browsers since July 2023:
ChromeTrack your progress - it's free!
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4