Last active
November 10, 2022 20:17
-
-
Save nickihastings/afab766a04bd10b2161f1bad3e982f65 to your computer and use it in GitHub Desktop.
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 = {…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function sym(args) { | |
//Put the arguments into an array | |
var arrArgs = Array.prototype.slice.call(arguments); | |
//Function to compare two arrays by reducing each one in | |
//comparison with the other. Check if the item in first array | |
//is also in the second array, if it isn't push it to the accumulator. | |
//then repeat the other way around. | |
function compareArrays(arr1, arr2){ | |
var arr1red = arr1.reduce(function(collect, current){ | |
//to remove doubles, check the item is not already collected. | |
if(!arr2.includes(current) && !collect.includes(current)){ | |
collect.push(current); | |
} | |
return collect; | |
},[]); | |
var arr2red = arr2.reduce(function(collect, current){ | |
if(!arr1.includes(current) && !collect.includes(current)){ | |
collect.push(current); | |
} | |
return collect; | |
},[]); | |
//join the two arrays together and return the result | |
return arr1red.concat(arr2red); | |
} | |
//Reduce the arguments array to a single array that contains only elements | |
//that are the symmetric difference. (First compare the first two arrays, then | |
//compare the result of that with the next array); | |
return arrArgs.reduce(compareArrays); | |
} | |
sym([1, 2, 3], [5, 2, 1, 4]); | |
sym([1, 2, 5], [2, 3, 5], [3, 4, 5]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very nice solution