JS數組操作:去重,交集,並集,差集


1. 數組去重

方法一:

function unique(arr) { //定義常量 res,值為一個Map對象實例 const res = new Map(); //返回arr數組過濾后的結果,結果為一個數組 //過濾條件是,如果res中沒有某個鍵,就設置這個鍵的值為1 return arr.filter((a) => !res.has(a) && res.set(a, 1)) }

方法二:

function unique(arr) { //通過Set對象,對數組去重,結果又返回一個Set對象 //通過from方法,將Set對象轉為數組 return Array.from(new Set(arr)) }

方法三:

function unique(arr) {
  return [...new Set(arr)]
}

2. 數據求交集、並集、差集

a = [1, 2, 3]

b = [2, 4, 5]

方法一:

ES7新增了一個Array.prototype.includes的數組方法,用於返回一個數組是否包含指定元素,結合filter方法

// 並集
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中新增的一個Array.from方法,用於將類數組對象和可遍歷對象轉化為數組。只要類數組有length長度,基本都可以轉化為數組。結合Set結構實現數學集求解。

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]

 

參考:

https://segmentfault.com/a/1190000011861891

https://excaliburhan.com/post/js-set-operation.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM