FreeCode Camp Algorithms: Find the Symmetric Difference

Create a function that takes two or more arrays and returns an array of the symmetric difference (or ) of the provided arrays.
Given two sets (for example set A = {1, 2, 3}and set B = {2, 3, 4}), the mathematical term "symmetric difference" of two sets is the set of elements which are in either of the two sets, but not in both (A △ B = C = {1, 4}). For every additional symmetric difference you take (say on a set D = {2, 3}), you should get the set with elements which are in either of the two the sets but not both (C △ D = {1, 4} △ {2, 3} = {1, 2, 3, 4}). The resulting array must contain only unique values (no duplicates).

function sym(args) {
let arr = [...arguments];

function toCompare(arr1, arr2) {
let arr3 = [];
for (let i = 0; i < arr1.length; i++) {
if (!arr2.includes(arr1[i])) {
if (!arr3.includes(arr1[i])) { //to avoid duplicate entries
arr3.push(arr1[i]);
}
}
}
for (let i = 0; i < arr2.length; i++) {
if (!arr1.includes(arr2[i])) {
if (!arr3.includes(arr2[i])) {
arr3.push(arr2[i]);
}
}
}
return arr3;
}

return arr.reduce(toCompare); //don't call function yet with ()
}

sym([1, 2, 3], [5, 2, 1, 4]);

Comments

Popular posts from this blog

Code Wars: longest_palindrome (6 kyu)

Code Wars: Data Reverse (6 kyu)

Code Wars: Replace With Alphabet Position