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

Array.prototype.toSorted() - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

Array.prototype.toSorted()

Baseline

20237

toSorted() Array sort()

js
toSorted()
toSorted(compareFn)

compareFn

Unicode 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 length - 1 0

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]

ECMAScript 2027 LanguageSpecification
# sec-array.prototype.tosorted


Web Proxy Viewer  |  New URL  |  Original Page