JS 找出两个数组中的交集 & 找出两个数组中的并集

1.找出两个数组中的交集?
  • 方法一(常规for循环)
let arr1 = [1,2,3,4]
let arr2 = [4,5,6]

let Intersection = []
for(let i = 0; i < arr1.length;i++){
  let _item = arr1[i]
  for(let j = 0; j < arr2.length;j++){
    if(_item === arr2[j]){
        Intersection.push(_item)
     }
  }
}
console.log(Intersection) //[4]
  • 方法二(利用filter和includes)
let arr1 = [1,2,3,4]
let arr2 = [4,5,6]

console.log(arr1.filter(item => arr2.includes(item))) //[4]
  • 方法三(reduce)
let arr1 = [1,2,3,4]
let arr2 = [4,5,6]
let _arr = arr1.concat(arr2).sort()

let result = []
_arr.reduce((pre,now) => {
  if(pre === now){
    result.push(now)
  }
  return now
 })
console.log(result) //[4]
2.找出两个数组中的并集?
  • 方法一(利用解构赋值...和Set的唯一性)
let arr1 = [1,2,3,4]
let arr2 = [4,5,6]
let result = [...new Set(arr1.concat(arr2))]
console.log(result) //[1, 2, 3, 4, 5, 6]
  • 方法二(reduce)
let arr1 = [1,2,3,4]
let arr2 = [4,5,6]
let _arr = [...arr1,...arr2].sort()

let result = []
_arr.reduce((pre,now) => {
 if(pre !== now){
    result.push(now)
  }
  return now
})
console.log(result)  //[1, 2, 3, 4, 5, 6]
  • 方法三(转json对象)
let arr1 = [1, 2, 3]
let arr2 = [4, 5, 3, 6]    
let obj = {}
arr1.forEach(item => {
  obj[item] = item
  console.log(obj) //{ 1: 1, 2: 2, 3: 3 }
})
arr2.forEach(item => {
  obj[item] = item
  console.log(obj)}) // { 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6 }
let result = Object.values(obj)
console.log(result)  //[1, 2, 3, 4, 5, 6]

你可能感兴趣的:(JS 找出两个数组中的交集 & 找出两个数组中的并集)