JavaScript 中如何对集合进行排序
在 JavaScript 中对集合进行排序:
- 使用
Array.from()
方法将 Set 转换为数组。 - 使用
Array.sort()
方法对数组进行排序。 - 将数组转换回 Set 集合对象。
// ✅ Sort a Set containing Strings
const set1 = new Set(['c', 'b', 'a']);
const sortedArray = Array.from(set1).sort();
console.log(sortedArray); // 👉️ ['a', 'b', 'c']
const sortedSet = new Set(sortedArray);
console.log(sortedSet); // 👉️ {'a', 'b', 'c'}
如果需要对包含数字的 Set 进行排序,则必须将函数传递给 Array.sort()
方法。
// ✅ Sort a Set containing Numbers
const set1 = new Set([300, 100, 700]);
// 👇️ sorts numbers in Ascending order
const sortedArray = Array.from(set1).sort((a, b) => a - b);
console.log(sortedArray); // 👉️ [100, 300, 700]
const sortedSet = new Set(sortedArray);
console.log(sortedSet); // 👉️ {100, 300, 700}
我们使用 Array.from()
方法将 Set 对象转换为数组,因此我们可以对数组调用 Array.sort() 方法。
请注意
,在对数字进行排序时,我们必须将一个函数作为参数传递给sort()
方法,而对于字符串,我们不需要。
我们传递给 sort()
方法的参数是一个定义排序顺序的函数。
如果我们不提供该参数,数组元素将转换为字符串并根据其 UTF-816
代码单元值进行排序。
这不是我们在处理包含数字的 Set 对象时想要的,但是,这正是我们在比较字符串时想要的。
对数组进行排序后,我们将其传递给 Set()
构造函数以将其转换回 Set。
如果必须经常这样做,请定义可重用的函数。
function sortStringSet(set) {
const sortedArray = Array.from(set).sort();
const sortedSet = new Set(sortedArray);
return sortedSet;
}
// 👇️ Set(3) { 'a', 'b', 'c' }
console.log(sortStringSet(new Set(['c', 'b', 'a'])));
// 👇️ Set(3) { 'a', 'c', 'z' }
console.log(sortStringSet(new Set(['c', 'z', 'a'])));
sortStringSet()
函数将包含字符串的 Set 作为参数,并对 Set 进行排序。
我们还可以定义 sortNumbersSet()
函数。
function sortNumbersSet(set) {
const sortedArray = Array.from(set).sort((a, b) => a - b);
const sortedSet = new Set(sortedArray);
return sortedSet;
}
// 👇️ Set(3) { 100, 300, 700 }
console.log(sortNumbersSet(new Set([700, 100, 300])));
// 👇️ Set(3) { 100, 500, 600 }
console.log(sortNumbersSet(new Set([500, 600, 100])));
该函数将数字 Set 作为参数并对 Set 进行排序。
使用扩展语法 (…) 对集合进行排序
或者,我们可以使用扩展语法 ...
将 Set 转换为数组。
// ✅ Sort a Set object that contains strings
const set1 = new Set(['c', 'b', 'a']);
const sortedArray = [...set1].sort();
console.log(sortedArray); // 👉️ [ 'a', 'b', 'c' ]
const sortedSet = new Set(sortedArray);
console.log(sortedSet); // 👉️ {'a', 'b', 'c'}
如果我们的 Set 对象包含数字,请将函数传递给 Array.sort()
方法。
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}
代码示例实现与使用 Array.from()
方法的代码示例相同的结果。
扩展语法
...
只是将 Set 的元素解包到一个数组中。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。