JavaScript toSorted 方法
最后修改于 2025 年 4 月 4 日
在本文中,我们将展示如何使用 JavaScript 中的 toSorted 方法对数组进行排序。
数组排序
数组排序是将元素按特定顺序排列的操作。 toSorted 方法默认创建一个新的数组,其中的元素按升序排列。 与 sort 不同,它不会修改原始数组。
此方法在 ECMAScript 2023 中引入,作为 sort 的更安全的替代方案。 它通过返回一个新的已排序数组来保持不可变性,同时保持原始数组不变。 这在函数式编程中特别有用。
toSorted 方法可以接受一个可选的比较函数作为参数。 此函数决定元素的排序顺序。 如果没有比较函数,元素将被转换为字符串并按 UTF-16 代码单元排序。
基本 toSorted 示例
以下示例演示了 toSorted 方法的基本用法。
const numbers = [3, 1, 4, 1, 5, 9]; const sortedNumbers = numbers.toSorted(); console.log(numbers); // Original array unchanged console.log(sortedNumbers); // New sorted array
我们创建一个数字数组并对它们进行排序。 原始数组保持不变。 toSorted() 方法返回一个新的数组,其中元素按升序排列。
$ node main.js [ 3, 1, 4, 1, 5, 9 ] [ 1, 1, 3, 4, 5, 9 ]
字符串排序
toSorted 方法也适用于字符串元素。
const fruits = ['banana', 'apple', 'cherry', 'date']; const sortedFruits = fruits.toSorted(); console.log(fruits); console.log(sortedFruits);
我们按字母顺序对字符串数组进行排序。 默认情况下,字符串比较区分大小写,并且基于 UTF-16 代码单元值。 原始数组保持不变。
$ node main.js [ 'banana', 'apple', 'cherry', 'date' ] [ 'apple', 'banana', 'cherry', 'date' ]
使用比较函数
toSorted() 方法可以接受一个比较函数来进行自定义排序。
const numbers = [10, 5, 8, 2, 1]; const descending = numbers.toSorted((a, b) => b - a); console.log(numbers); console.log(descending);
我们使用比较函数按降序对数字进行排序。 该函数返回正值、负值或零值,以确定排序顺序。 原始数组被保留。
$ node main.js [ 10, 5, 8, 2, 1 ] [ 10, 8, 5, 2, 1 ]
按属性对对象排序
我们可以使用基于属性的比较函数对对象数组进行排序。
const users = [
{ name: 'John', age: 25 },
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 20 }
];
const byAge = users.toSorted((a, b) => a.age - b.age);
console.log(byAge);
我们按其 age 属性对对象数组进行排序。 比较函数提取 age 值以进行比较。 这会创建一个新的已排序数组,而不会修改原始数组。
$ node main.js
[
{ name: 'Bob', age: 20 },
{ name: 'John', age: 25 },
{ name: 'Alice', age: 30 }
]
不区分大小写的字符串排序
对于不区分大小写的排序,我们需要一个自定义比较函数。
const words = ['Apple', 'banana', 'cherry', 'Date'];
const caseInsensitive = words.toSorted((a, b) =>
a.localeCompare(b, undefined, { sensitivity: 'base' })
);
console.log(words);
console.log(caseInsensitive);
我们使用带有基本敏感度选项的 localeCompare 对字符串进行不区分大小写的排序。 这将大写字母和小写字母视为等同。 原始数组保持不变。
$ node main.js [ 'Apple', 'banana', 'cherry', 'Date' ] [ 'Apple', 'banana', 'cherry', 'Date' ]
来源
在本文中,我们演示了如何使用 toSorted 方法对 JavaScript 中的数组进行排序,同时保留原始数组。
作者
列出 所有 JS 数组函数。