Skip to content
On this page

nion&intersect 并集与交集

js
// 利用Set求数组的交集与并集
let arr1 = [1, 2, 3, 4]
let arr2 = [3, 4, 5, 6]

// 并集
let set3 = new Set(arr1)
let set4 = new Set(arr2)
// 合并去重就是答案
let union = new Set([...set3, ...set4])
console.log(union) // 1, 2, 3, 4, 5, 6


// 交集
let set1 = new Set(arr1)
let set2 = new Set(arr2)
// 使用filter+has过滤后的是已存在的,但是有可能重复,使用Set就去重了
let intersect = new Set([...set1].filter(item => set2.has(item)))
console.log(intersect) // 3, 4
// 利用Set求数组的交集与并集
let arr1 = [1, 2, 3, 4]
let arr2 = [3, 4, 5, 6]

// 并集
let set3 = new Set(arr1)
let set4 = new Set(arr2)
// 合并去重就是答案
let union = new Set([...set3, ...set4])
console.log(union) // 1, 2, 3, 4, 5, 6


// 交集
let set1 = new Set(arr1)
let set2 = new Set(arr2)
// 使用filter+has过滤后的是已存在的,但是有可能重复,使用Set就去重了
let intersect = new Set([...set1].filter(item => set2.has(item)))
console.log(intersect) // 3, 4