集合交集算法
给出两个集合 (如集合 A = {1, 2, 3}
和集合B = {2, 3, 4}
),
而数学术语 “对等差分” 的集合就是指由所有只在两个集合其中之一的元素组成的集合(A △ B = C = {1, 4}
).
对于传入的额外集合 (如 D = {2, 3}
),
你应该按照前面原则求前两个集合的结果与新集合的对等差分集合 (C △ D = {1, 4} △ {2, 3} = {1, 2, 3, 4}
).
代码示例:
function sym(...args) {
console.log(...args)
return args.reduce((total, current)=>{
let diff = total.filter(x=>!current.includes(x)).concat(current.filter(x=>!total.includes(x)));
// return Array.from(new Set([...diff]));
return Array.from(new Set(diff))
});
}
sym([1, 2, 3], [5, 2, 1, 4]); // [3, 4, 5]