JavaScript TypedArray.prototype.toSorted() Method

The toSorted() method, presented in ECMAScript 2023 or (ES2023) affords a secure and efficient manner of ordering elements of TypedArray in ascending order.

The toSorted() method of TypedArray instances is the copying version of the sort() method, it gives back a new typed array with sorted elements. Its algorithm is the same as that of Array.prototype.toSorted one apart from it uses numeric sorting rather than string sorting by default.

Syntax

toSorted()
toSorted(compareFn)

Parameter:

  • compareFn: A function that determines the order of the elements, if omitted, the typed array elements are sorted according to a numeric value.

Return Type:

Returns a new TypedArray that has been created with elements in ascending order.

Example 1: In this example, we are sorting numbers.

JavaScript
const numbers = new Int16Array([5, 1, 8, 3, 2]);

const sortedNumbers = numbers.toSorted();

console.log(sortedNumbers); 
console.log(numbers);      

Output:

Int16Array(5) [1, 2, 3, 5, 8]
Int16Array(5) [5, 1, 8, 3, 2]

Example 2: In this example, we are sorting strings.

JavaScript
const fruits = new Uint8Array([79, 97, 100, 101, 82, 99]);

function stringCompare(a, b) {
  return String.fromCharCode(a).localeCompare(String.fromCharCode(b));
}

const sortedFruits = fruits.toSorted(stringCompare);

console.log(String.fromCharCode.apply(null, sortedFruits));

Output:

acdeOR

Supported Browsers

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari

Contact Us