数组操作:交集、差集、并集

1、求交集

利用filter测试数组中的每一个元素,在使用includes来判断是否有相同元素,如果有相同的元素则将
返回在一个新的数组中
实例:
let a=[1,2,3,4,5,6],b=[4,5,6,7,8,9];
方法1

 let intersection = a.filter(v => b.includes(v)) // [4,5,6]

方法2

  let aSet = new Set(a)
  let bSet = new Set(b)
  let intersection = Array.from(new Set(a.filter(v => bSet.has(v))))  

2、求并集

方法1

  let union = a.concat(b.filter(v => !a.includes(v))) // [1,2,3,4,5,6,7,8,9]

方法2

 let aSet = new Set(a)
 let bSet = new Set(b)
 let union = Array.from(new Set(a.concat(b)))

3、求差集

方法1

let difference = a.concat(b).filter(v => !a.includes(v) || !b.includes(v)) // [1,2,3,7,8,9]

方法2

let aSet = new Set(a)
let bSet = new Set(b)
let difference = Array.from(new Set(a.concat(b).filter(v => !aSet.has(v) || !bSet.has(v))))  

你可能感兴趣的:(数组操作:交集、差集、并集)