在 JavaScript 中对集合进行排序
How to sort a Set in JavaScript
Set
在 JavaScript 中对 a 进行排序:
- 使用 方法将 转换
Set
为数组Array.from()
。 - 使用
Array.sort()
方法对数组进行排序。 - 将数组转换回
Set
对象。
索引.js
/** * 👇️ SORT a NUMBERS Set */ const numbersSet = new Set([300, 100, 700]); // 👉️ sorts numbers in Ascending order const sortedNumbers = Array.from(numbersSet).sort((a, b) => a - b); console.log(sortedNumbers); // 👉️ [100, 300, 700] const sortedNumbersSet = new Set(sortedNumbers); console.log(sortedNumbersSet); // 👉️ {100, 300, 700} /** * 👇️ SORT a STRINGS Set */ const stringsSet = new Set(['c', 'b', 'a']); const sortedStrings = Array.from(stringsSet).sort(); console.log(sortedStrings); // 👉️ ['a', 'b', 'c'] const sortedStringsSet = new Set(sortedStrings); console.log(sortedStringsSet); // 👉️ {'a', 'b', 'c'}
我们使用
Array.from
方法从Set
对象创建一个数组。
然后我们在数组上调用
Array.sort方法。
请注意,在对数字进行排序时,我们必须将函数作为参数传递给sort
方法,而对于字符串,我们不需要。
我们传递给该sort
方法的参数是一个定义排序顺序的函数。
如果您不提供此参数,数组元素将转换为字符串并根据其 UTF-16 代码单元值进行排序。
这不是我们在处理
这不是我们在处理
Sets
包含数字时想要的,但这正是我们在比较字符串时想要的。对数组排序后,我们必须将其传递给
Set 构造函数
以将其转换回Set
. 我们可以按元素插入顺序进行迭代Sets
。
Array.from
在使用 TypeScript 时推荐使用该方法,因为编译器在将扩展运算符 (…) 与迭代器一起使用时经常会报错。下面是相同的示例,但是这次我们使用
扩展运算符 (…)
而不是Array.from
.
索引.js
const numbersSet = new Set([300, 100, 700]); const sortedNumbers = [...numbersSet].sort((a, b) => a - b); console.log(sortedNumbers); // 👉️ [100, 300, 700] const sortedNumbersSet = new Set(sortedNumbers); console.log(sortedNumbersSet); // 👉️ {100, 300, 700} /** * 👇️ SORT a STRINGS Set */ const stringsSet = new Set(['c', 'b', 'a']); const sortedStrings = [...stringsSet].sort(); console.log(sortedStrings); // 👉️ ['c', 'b', 'a'] const sortedStringsSet = new Set(sortedStrings); console.log(sortedStringsSet); // 👉️ {'a', 'b', 'c'}
Set
扩展运算符 (…) 是将 a转换为数组的最常用方法。