var c = a.filter(function(v){ return b.indexOf(v) > -1 }) var d = a.filter(function(v){ return b.indexOf(v) == -1 }) var e = a.filter(function(v){ return !(b.indexOf(v) > -1) }) .concat(b.filter(function(v){ return !(a.indexOf(v) > -1)})) var f = a.concat(b.filter(function(v){ return !(a.indexOf(v) > -1)})); //a与b的交集c: [2, 4] //a与b的差集d: [1, 3, 5] //a与b的补集e: [1, 3, 5, 6, 8, 10] //a与b的并集f: [1, 2, 3, 4, 5, 6, 8, 10]
  1. ES6语法
var a = [1,2,3,4,5]
var b = [2,4,6,8,10]
console.log("数组a:", a);
console.log("数组b:", b);
var sa = new Set(a);
var sb = new Set(b);
// 交集
let c= a.filter(x => sb.has(x));
// 差集
let d= a.filter(x => !sb.has(x));
// 补集
let e= [...a.filter(x => !sb.has(x)), ...b.filter(x => !sa.has(x))];
// 并集
let f= Array.from(new Set([...a, ...b]));
//a与b的交集c: [2, 4]
//a与b的差集d: [1, 3, 5]
//a与b的补集e: [1, 3, 5, 6, 8, 10]
//a与b的并集f: [1, 2, 3, 4, 5, 6, 8, 10]

数组对象

  1. 直接用ES6语法会少很多代码
let a=[{id:1,a:123,b:1234},{id:2,a:123,b:1234},{id:5,a:123,b:1234}];
let b=[{id:1,a:123,b:1234},{id:2,a:123,b:1234},{id:3,a:123,b:1234},{id:4,a:123,b:1234}];
//取交集
let c= [...b].filter(x => [...a].some(y => y.id === x.id));
//取差集
let d= [...b].filter(x => [...a].every(y => y.id !== x.id));
// 补集(这里是将两个交集相加了)
let d1= [...a].filter(x => [...b].every(y => y.id !== x.id));
let e = d.concat(d1);
// 并集(交集+补集)
let f = c.concat(e);
//a与b的交集c: [{id:1,a:123,b:1234},{id:2,a:123,b:1234}]
//a与b的差集d: [{id:3,a:123,b:1234},{id:4,a:123,b:1234}]
//a与b的补集e: [{id:3,a:123,b:1234},{id:4,a:123,b:1234},{id:5,a:123,b:1234}]
//a与b的并集f:  [{id:1,a:123,b:1234},{id:2,a:123,b:1234},{id:3,a:123,b:1234},{id:4,a:123,b:1234},{id:5,a:123,b:1234}]