Array

Array.prototype.toSorted

Returns a new array with the elements sorted in ascending order, without modifying the original array

Syntax

JavaScript
array.toSorted(compareFn?)

Parameters

ParameterTypeDescription
compareFn(a, b) => numberFunction that defines the sort order

Return Value

A new sorted array

Examples

Basic Usage
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)
Practical Example
const words = ['banana', 'apple', 'cherry'];
console.log(words.toSorted()); // ['apple', 'banana', 'cherry']
Advanced Usage
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

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.