Typed Array sort()
Examples
// Create a Typed Array
const myArr = Int32Array.of(40, 100, 1, 5, 25, 10);
// Sort the Array
myArr.sort();
Try it Yourself »
More Examples Below !
Description
The sort()
method sorts the elements of a typed array.
The sort()
method overwrites 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.sort(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 | The original array with the elements 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
myArr.sort();
// Reverse the Array
myArr.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 array using a function
myArr.sort(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
myArr.sort();
let lowest = myArr.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
myArr.sort();
let highest = myArr.at(-1);
Try it Yourself »
JavaScript Typed Arrays
Browser Support
Typed-array.sort()
is an ECMAScript6 (ES6 2015) feature.
JavaScript 2015 is fully supported in all modern browsers since June 2017:
Chrome 51 | Edge 15 | Firefox 54 | Safari 10 | Opera 38 |
May 2016 | Apr 2017 | Jun 2017 | Sep 2016 | Jun 2016 |