用法
ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。
Set
本身是一个构造函数,用来生成 Set 数据结构。add()
方法向 Set 结构加入成员。例:
const s = new Set();
[2, 3, 2, 4, 4, 5, 2].forEach(x => s.add(x));
for (let i of s) {
console.log(i);
}
// 2 3 4 5
上面代码通过add()方法加入成员,遍历输出后可见没有重复的值。
Set
函数可以接受一个数组(或者具有 iterable 接口的其他数据结构)作为参数,用来初始化。所以可以用Set来给数组去重。例:
//单个数组去重
let array = [1, 2, 2, 3, 3, 4, 5, 5]
let uniqueArray = new Set(array)
console.log(uniqueArray)
//两个数组去重
const array1 = [1, 2, 3, 4]
const array2 = [3, 4, 5, 6]
// 将两个数组合并并使用Set去重
const mergedArray = new Set([...array1, ...array2])
console.log(mergedArray)
// 计算两个数组的交集
const intersection = array1.filter((item) => array2.includes(item))
console.log(intersection)
// 计算两个数组的并集
const union = [...new Set([...array1, ...array2])]
console.log(union)
// 计算两个数组的差集
// const difference = array1.filter((item) => !array2.includes(item))
// console.log(difference)
const difference1 = array1.filter((item) => !array2.includes(item))
const difference2 = array2.filter((item) => !array1.includes(item))
const symmetricDifference =