Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Array.prototype.toSorted()

Baseline2023
Newly available

ThetoSorted() method ofArray instances is thecopying version of thesort() method. It returns a new array with the elements sorted in ascending order.

Syntax

js
toSorted()toSorted(compareFn)

Parameters

compareFnOptional

A function that determines the order of the elements. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. Seesort() for more information.

Return value

A new array with the elements sorted in ascending order.

Description

Seesort() for more information on thecompareFn parameter.

When used onsparse arrays, thetoSorted() method iterates empty slots as if they have the valueundefined.

ThetoSorted() method isgeneric. It only expects thethis value to have alength property and integer-keyed properties.

Examples

Sorting an array

js
const months = ["Mar", "Jan", "Feb", "Dec"];const sortedMonths = months.toSorted();console.log(sortedMonths); // ['Dec', 'Feb', 'Jan', 'Mar']console.log(months); // ['Mar', 'Jan', 'Feb', 'Dec']const values = [1, 10, 21, 2];const sortedValues = values.toSorted((a, b) => a - b);console.log(sortedValues); // [1, 2, 10, 21]console.log(values); // [1, 10, 21, 2]

For more usage examples, seesort().

Using toSorted() on sparse arrays

Empty slots are sorted as if they have the valueundefined. They are always sorted to the end of the array andcompareFn is not called for them.

js
console.log(["a", "c", , "b"].toSorted()); // ['a', 'b', 'c', undefined]console.log([, undefined, "a", "b"].toSorted()); // ["a", "b", undefined, undefined]

Calling toSorted() on non-array objects

ThetoSorted() method reads thelength property ofthis. It then collects all existing integer-keyed properties in the range of0 tolength - 1, sorts them, and writes them into a new array.

js
const arrayLike = {  length: 3,  unrelated: "foo",  0: 5,  2: 4,  3: 3, // ignored by toSorted() since length is 3};console.log(Array.prototype.toSorted.call(arrayLike));// [4, 5, undefined]

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-array.prototype.tosorted

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp