两个数组取相同、不同项
利用
new Set生成唯一值的set对象,然后用filter过滤即可。
相同项
const difference = (arr1, arr2) => {
let s = new Set(arr2);
return arr1.filter(x => s.has(x))
}
// difference([1,2,3], [1,2]) -> [3]
1
2
3
4
5
2
3
4
5
不同项
const intersection = (arr1, arr2) => {
let s = new Set(arr2);
return arr1.filter(x => !s.has(x))
}
// intersection([1,2,3], [4,3,2]) -> [2,3]
1
2
3
4
5
2
3
4
5