Array.prototype.toSorted
Returns a new array with the elements sorted in ascending order, without modifying the original array
Syntax
array.toSorted(compareFn?)Parameters
| Parameter | Type | Description |
|---|---|---|
| compareFn | (a, b) => number | Function that defines the sort order |
Return Value
A new sorted array
Examples
const numbers = [3, 1, 4, 1, 5];
const sorted = numbers.toSorted((a, b) => a - b);
console.log(sorted); // [1, 1, 3, 4, 5]
console.log(numbers); // [3, 1, 4, 1, 5] (unchanged)const words = ['banana', 'apple', 'cherry'];
console.log(words.toSorted()); // ['apple', 'banana', 'cherry']const data = [{ n: 3 }, { n: 1 }, { n: 2 }];
const sorted = data.toSorted((a, b) => a.n - b.n);
console.log(sorted.map(d => d.n)); // [1, 2, 3]Understanding Array.prototype.toSorted
The Array.prototype.toSorted method in JavaScript returns a new array with the elements sorted in ascending order, without modifying the original array. It belongs to the Array object and is one of the most widely used methods for working with array values in modern JavaScript and TypeScript applications.
The method signature is array.toSorted(compareFn?). It accepts 1 parameter: compareFn. When called, it returns a new sorted array. Understanding when and how to use toSorted() helps you write more expressive, readable code.
Common use cases for Array.prototype.toSorted include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like array-sort, array-toreversed, array-tospliced, enabling you to chain operations together for complex data manipulation pipelines.
Supported in Chrome 110+, Firefox 115+, Safari 16+, Edge 110+, and Node.js 20+.
Browser Compatibility
Supported in Chrome 110+, Firefox 115+, Safari 16+, Edge 110+, and Node.js 20+.
Related Methods
Array.prototype.sortSorts the elements of an array in place and returns the sorted array
Array.prototype.toReversedReturns a new array with the elements in reversed order, without modifying the original array
Array.prototype.toSplicedReturns a new array with some elements removed and/or replaced at a given index, without modifying the original array
Array.prototype.withReturns a new array with the element at the given index replaced with the given value, without modifying the original array
More Array Methods
Other methods in the Array object
Related Tools
More Array Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.