JavaScript 陣列求交集、差集

JavaScript 陣列求交集、差集

在面試題目中常遇到的題目,陣列的交集、差集、補集等這類的題目,記錄一篇解法與自己的理解以便於加深自己的印象,不囉唆直接上 code 。

使用方法

Array.filter
filter() 方法會建立一個經指定之函式運算後,由原陣列中通過該函式檢驗之元素所構成的新陣列。

Set
Set 物件可讓你儲存任何類型的唯一值(unique),不論是基本型別(primitive)值或物件參考(references)。

jQuery
大家的好朋友就不用多說了

交集

求出兩個陣列的交集

Array.filter

let arr1 = [1,2,3,4,5]
let arr2 = [2,4,6,8,10]

let result =arr1.filter((e) => {
  return arr2.indexOf(e) > -1
})

console.log(r) // [2,4]

Set

let arr1 = [1,2,3,4,5]
let arr2 = [2,4,6,8,10]

let set1 = new Set(arr1)
let set2 = new Set(arr2)

let result = arr1.filter((e)=>{
  return set2.has(e)
})

console.log(result) // [2, 4]

jQuery

let arr1 = [1,2,3,4,5]
let arr2 = [2,4,6,8,10]

let result = $(arr1).filter(arr2).toArray()

console.log(result) // [2, 4]

差集

求出兩個陣列的差集

Array.filter

let arr1 = [1,2,3,4,5]
let arr2 = [2,4,6,8,10]

let result = arr1.filter((e)=>{
  return arr2.indexOf(e) === -1
})

console.log(result) // [1,3,5]

Set

let arr1 = [1,2,3,4,5]
let arr2 = [2,4,6,8,10]

let set1 = new Set(arr1)
let set2 = new Set(arr2)

let result = arr1.filter((e)=>{
  return !set2.has(e)
})

console.log(result) // [1,3,5]

jQuery

let arr1 = [1,2,3,4,5]
let arr2 = [2,4,6,8,10]

let result = $(arr1).not(arr2).toArray()

console.log(result) // [1, 3, 5]

絕對差集(補集)

求兩個陣列的補集

Array.filter

let arr1 = [1,2,3,4,5]
let arr2 = [2,4,6,8,10]

let result = arr1.filter((e)=>{
  return arr2.indexOf(e) === -1
}).concat(arr2.filter((f)=>{
  return arr1.indexOf(f) === -1
}))

console.log(result) // [1, 3, 5, 6, 8, 10]

Set

let arr1 = [1,2,3,4,5]
let arr2 = [2,4,6,8,10]

let set1 = new Set(arr1)
let set2 = new Set(arr2)

let result = [...arr1.filter( x => !set2.has(x) ),
              ...arr2.filter( y => !set1.has(y) )
             ]

console.log(result) // [1, 3, 5, 6, 8, 10]

jQuery

let arr1 = [1,2,3,4,5]
let arr2 = [2,4,6,8,10]

let result = $(arr1).not(arr2).toArray().concat($(arr2).not(arr1).toArray())

console.log(result)

聯集

求兩個陣列的聯集

Array.filter

let arr1 = [1,2,3,4,5]
let arr2 = [2,4,6,8,10]

let result = arr1.concat(arr2.filter((e)=>{
 return arr1.indexOf(e) === -1
}))

console.log(result) // [1, 2, 3, 4, 5, 6, 8, 10]

Set

let arr1 = [1,2,3,4,5]
let arr2 = [2,4,6,8,10]

let set1 = new Set(arr1)
let set2 = new Set(arr2)

let result = Array.from(new Set([...arr1, ...arr2]))

console.log(result) // [1, 2, 3, 4, 5, 6, 8, 10]

jQuery

let arr1 = [1,2,3,4,5]
let arr2 = [2,4,6,8,10]

let result = $.merge(arr1, arr2.filter((x)=>arr1.indexOf(x) === -1 ))

console.log(result) // [1, 2, 3, 4, 5, 6, 8, 10]