1培漏、ES7實現(xiàn)方式
ES7中新增一個Array.prototype.includes():includes() 方法用來判斷一個數(shù)組是否包含一個指定的值胡本,根據(jù)情況牌柄,如果包含則返回 true珊佣,否則返回false。我們可以將includes方法與filter方法結(jié)合實現(xiàn)求數(shù)組的并集咒锻、交集和差集守屉,如下:
let a = [1,2,3];
let b = [2,4,5];
//并集
console.log(a.concat(b.filter(v => !a.includes(v))));//[1, 2, 3, 4, 5]
//交集
console.log(a.filter(v => b.includes(v)));// [2]
//差集
console.log(a.concat(b).filter(v => a.includes(v) && !b.includes(v)));//[1, 3]
2、ES6實現(xiàn)方式(利用Set數(shù)組去重的原理)
ES6中新增一個Array.from():該方法從一個類似數(shù)組或可迭代對象中創(chuàng)建一個新的數(shù)組實例(即將類數(shù)組對象和可遍歷對象轉(zhuǎn)化為數(shù)組拇泛。只要類數(shù)組有l(wèi)ength長度须板,基本都可以轉(zhuǎn)化為數(shù)組)兢卵。為我們將該方法與Set結(jié)構(gòu)結(jié)合實現(xiàn)數(shù)組的并集、交集和差集秽荤,如下:
let a = [1,2,3];
let b = [2,4,5];
let aSet = new Set([1,2,3]);
let bSet = new Set([2,4,5]);
//并集
let union = Array.from(new Set(a.concat(b)));
console.log(union );//[1, 2, 3, 4, 5]
//交集
let intersection = Array.from(new Set(a.filter(v => bSet.has(v))));
console.log(intersection);//[2]
//差集
let differenceNew = Array.from(new Set(a.concat(b).filter(v => aSet.has(v) && !bSet.has(v))));
console.log(differenceNew);//[1,3]
3、ES5實現(xiàn)方式
ES5可以利用filter和indexOf進行數(shù)學(xué)集操作课兄,但是,由于indexOf方法中NaN永遠返回-1烟阐,所以需要進行兼容處理,即分兩種情況:
(1)不考慮NaN的情況(數(shù)組中不含NaN)
var a = [1,2,3];
var b = [2,4,5];
// 并集
var union = a.concat(b.filter(function(v) {
return a.indexOf(v) === -1
}))
// 交集
var intersection = a.filter(function(v){
return b.indexOf(v) > -1
})
// 差集
var difference = a.filter(function(v){
return b.indexOf(v) === -1
})
console.log(union); // [1,2,3,4,5]
console.log(intersection);// [2]
console.log(difference);// [1,3]
(2)考慮NaN的情況
var a = [1, 2, 3, NaN];
var b = [2, 4, 5];
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] : [])
// 交集
var intersection = a.filter(function (v) {
return b.indexOf(v) > -1
}).concat(aHasNaN && bHasNaN ? [NaN] : [])
// 差集
var difference = a.filter(function (v) {
return b.indexOf(v) === -1 && !isNaN(v)
}).concat(aHasNaN && !bHasNaN ? [NaN] : [])
console.log(union);// [1,2,3,4,5,NaN]
console.log(intersection);// [2]
console.log(difference);//1,3,NaN