Returns the symmetric difference between two arrays, without filtering out duplicate values.
Create a Set
from each array, then use Array.prototype.filter()
on each of them to only keep values not contained in the other.
代码片段
const symmetricDifference = (a, b) => {
const sA = new Set(a),
sB = new Set(b);
return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))];
};
使用样例
symmetricDifference([1, 2, 3], [1, 2, 4]); // [3, 4]
symmetricDifference([1, 2, 2], [1, 3, 1]); // [2, 2, 3]