const serveralArr = [
[1,2,4,5,23,3,2,2,4,3,5,5],
[3,2,3,2,2,4,3,1,4,5,6],
[3,2,4,3,2,4,1,2,5],
[3,2,4,5,5,4,3,1,2,2],
[3,2,23,3,4,1,3,4,5,5,4,3,1,2,2],
[3,2,4,1,2,5,5,4,3,1,2,2],
[3,2,4,25,5,4,3,1,2,2],
]
// ES5 方法实现数学意义上的交集结果
const intersectNoRepeatFirst = serveralArr =>{
let minArr = serveralArr[0]
serveralArr.forEach(item =>{
if(item.length <minArr.length){
minArr = item
}
})
const result = []
minArr.forEach(item =>{
serveralArr.forEach(j =>{
if(j.includes(item) &&!result.includes(item)){
result.push(item)
}
})
})
return result
}
// ES6 方法实现数学意义上的交集结果
const intersectNoRepeatTwice = arrs =>{
return arrs.reduce(function(prev,cur){
// return [...new Set(cur.filter((item)=>prev.includes(item)))]
return Array.from(new Set(cur.filter((item)=>prev.includes(item))))
})
}
// 输出数学意义上的交集结果
console.log(intersectNoRepeatFirst(serveralArr), intersectNoRepeatTwice(serveralArr)) // =>(5) [3, 2, 4, 1, 5](5) [3, 2, 4, 5, 1]
// ES5 方法实现有重复元素的交集结果
const intersectRepeat = arr =>{
const result = []
const tempArr = []
arr.forEach(item =>{
const obj = {}
item.forEach(j =>{
if(obj.hasOwnProperty(j)){
obj[j] += 1
}else{
obj[j] = 1
}
})
tempArr.push(obj)
})
let arrr = tempArr[0]
tempArr.forEach(item =>{
if(item.length <arrr.length){
arrr = item
}
})
const newOjb = {}
Object.keys(arrr).forEach(item =>{
newOjb[item] = Math.min.apply(Math, tempArr.map(function(o) {return o[item]}))
})
Object.keys(newOjb).forEach(item =>{
if(newOjb[item]){
for(let i = 0i <newOjb[item]i++){
result.push(Number(item))
}
}
})
return result
}
// 输出有重复元素的交集结果
console.log(intersectRepeat(serveralArr)) // =>(9) [1, 2, 2, 2, 3, 3, 4, 4, 5]
相同的a.filter(function(v){returnb.indexOf(v)>-1})不同的 a.filter(function(v){ return !(b.indexOf(v) >-1) }).concat(b.filter(function(v){ return !(a.indexOf(v) >-1)}))