第164题 两个数组求交集和并集

    const arr1 = [1,3,4,6,7]
    const arr2 = [2,5,3,6,1]
    
    function getIntersection(arr1, arr2) {
      // 交集
    }
    function getUnion(arr1, arr2) {
      // 并集
    }
```**答案**  
```js
    // 交集
    function getIntersection(arr1, arr2) {
      const res = new Set()
      const set2 = new Set(arr2)
      for(let item of arr1) {
        if(set2.has(item)) { // 考虑性能:这里使用set的has比数组的includes快很多
          res.add(item) 
        }
      }
      return Array.from(res) // 转为数组返回
    }
    
    // 并集
    function getUnion(arr1, arr2) {
      const res = new Set(arr1)
      for(let item of arr2) {
        res.add(item) // 利用set的去重功能
      }
      return Array.from(res) // 转为数组返回
    }
    // 测试
    
    const arr1 = [1,3,4,6,7]
    const arr2 = [2,5,3,6,1]
    console.log('交集', getIntersection(arr1, arr2)) // 1,3,6
    console.log('并集', getUnion(arr1, arr2)) // 1,3,4,6,7,2,5
Last Updated:
Contributors: leeguooooo