[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ru/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 ..

toSorted() Array , . sort().

In this article

js
toSorted()
toSorted(compareFn)

compareFn

, . , , . sort() .

.

sort() compareFn.

toSorted() toSorted() , undefined.

toSorted() . , this length .

js
const months = ["", "", "", ""];
const sortedMonths = months.toSorted();
console.log(sortedMonths); // ["", "", "", ""]
console.log(months); // ["", "", "", ""]

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(["", "", , ""].toSorted()); // ["", "", "", undefined]
console.log([, undefined, "", ""].toSorted()); // ["", "", undefined, undefined]

toSorted() ,

arrayLike, , length . arrayLike length, 3, toSorted() 3. 0 length - 1. 1 , undefined.

js
const arrayLike = {
  length: 3,
  unrelated: "foo",
  0: 5,
  2: 4,
  3: 3, //   toSorted(),     3
};
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