[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted [Back]  [Original]

Array.prototype.toSorted() - JavaScript | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

Array.prototype.toSorted()

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 2023 7.

Array toSorted() sort() . .

In this article

js
toSorted()
toSorted(compareFn)

compareFn Optional

. . sort() .

.

compareFn sort() .

toSorted() undefined .

toSorted() . this length .

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]

sort() .

toSorted()

undefined . compareFn .

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

toSorted()

toSorted() this length . 0 length - 1 .

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

Specification
ECMAScript 2027 LanguageSpecification
# sec-array.prototype.tosorted


Web Proxy Viewer  |  New URL  |  Original Page