多个数组取交集
2020-09-15 本文已影响0人
羊绘霖
var profession = ["cat", "dog","pig","duck"];
var a = {
"cat": [1, 2, 3, "12", 4, 22, 11],
"pig": [2, 3, "12"],
"dog": [2, 4, 3, "12", 11],
"duck":[2,11]
};
var jiaoji = a.cat;
var re = profession.reduce(function(pre, cur, index, array) {
jiaoji = jiaoji.filter(function(n) {
return a[cur].indexOf(n) != -1;
});
return jiaoji;
},a.cat);
console.log(jiaoji);
// 并集
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]