1. 程式人生 > >JS陣列求並集,交集和差集

JS陣列求並集,交集和差集

es7: filter結合includes

   // 並集
   let union = a.concat(b.filter(v => !a.includes(v))) // [1,2,3,4,5]
   // 交集
   let intersection = a.filter(v => b.includes(v)) // [2]
   // 差集
   let difference = a.concat(b).filter(v => !a.includes(v) || !b.includes(v)) // [1,3,4,5]

es6: set資料結合Array.form

 let aSet = new Set(a)
   let bSet = new Set(b)
   // 並集
   let union = Array.from(new Set(a.concat(b))) // [1,2,3,4,5]
   // 交集
   let intersection = Array.from(new Set(a.filter(v => bSet.has(v)))) // [2]
   // 差集
   let difference = Array.from(new Set(a.concat(b).filter(v => !aSet.has(v) || !bSet.has(v)))) // [1,3,4,5]

ES5可以利用filter和indexOf進行數學集操作,但是,由於indexOf方法中NaN永遠返回-1,所以需要進行相容處理。

 // 不考慮NaN(陣列中不含NaN)
  // 並集
   var union = a.concat(b.filter(function(v) {
   return a.indexOf(v) === -1})) // [1,2,3,4,5]
   // 交集
   var intersection = a.filter(function(v){ return b.indexOf(v) > -1 }) // [2]
   // 差集
   var difference = a.filter(function(v){ return b.indexOf(v) === -1 }).concat(b.filter(function(v){ return a.indexOf(v) === -1 })) // [1,3,4,5]

  //考慮NaN
   var aHasNaN = a.some(function(v){ return isNaN(v) })
   var bHasNaN = b.some(function(v){ return isNaN(v) })
   // 並集
   var union = a.concat(b.filter(function(v) {
   return a.indexOf(v) === -1 && !isNaN(v)})).concat(!aHasNaN & bHasNaN ? [NaN] : []) // [1,2,3,4,5]
   // 交集
   var intersection = a.filter(function(v){ return b.indexOf(v) > -1 }).concat(aHasNaN & bHasNaN ? [NaN] : []) // [2]
   // 差集
   var difference = a.filter(function(v){ return b.indexOf(v) === -1 && !isNaN(v) }).concat(b.filter(function(v){ return a.indexOf(v) === -1 && !isNaN(v) })).concat(aHasNaN ^ bHasNaN ? [NaN] : []) // [1,3,4,5]