Typed Array toSorted()
Examples
// Create a Typed Array
const myArr = Int32Array.of(40, 100, 1, 5, 25, 10);
// Sort the Array into a new Array
const newArr = myArr.toSorted();
Try it Yourself »
More Examples Below !
Description
The toSorted()
method sorts the elements of an array into a new array.
The toSorted()
method does not change the original array.
Typed Array Sort Methods:
Method | Finds |
---|---|
reverse() | Reverses the order of the elements in an array |
sort() | Sorts the order of the elements in an array |
toReversed() | Reverses the elements of an array into a new array |
toSorted() | Sorts the elements of an array into a new array |
Syntax
typed-array.toSorted(compareFunction)
Parameters
Parameter | Description |
compareFunction |
Optional.
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} |
Note
Normal Arrays are sorted by alphabet. Typed Arrays are sorted by number.
Because of this, a compare function is not so often required for Typed Arrays.
Return Value
Type | Description |
Typed Array | A new array with the items sorted. |
Sort Descending
Sort and then reverse the order:
// Create a Typed Array
const myArr = Int32Array.of(40, 100, 1, 5, 25, 10);
// Sort the Array into a new Array
const newArr = myArr.sort();
// Reverse the new Array
newArr.reverse();
Try it Yourself »
Sort descending using a compare function:
// Create a Typed Array
const myArr = Int32Array.of(40, 100, 1, 5, 25, 10);
// Sort the Srray using a Function
const newArr = myArr.toSorted(function(a, b){return b - a});
Try it Yourself »
Find the Lowest Value
Find the lowest value:
// Create a Typed Array
const myArr = Int32Array.of(40, 100, 1, 5, 25, 10);
// Sort the Array into a new Array
const newArr = myArr.toSorted();
Get the lowest value
let lowest = newArr.at(0);
Try it Yourself »
Find the highest value:
// Create an Array
const myArr = Int32Array.of(40, 100, 1, 5, 25, 10);
// Sort the Array into a new Array
const newArr = myArr.toSorted();
Get the highest value
let highest = newArr.at(-1);
Try it Yourself »
JavaScript Typed Arrays
Browser Support
Typed-array.toSorted()
is an ES2023 feature.
JavaScript 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 |