{{ message }}

Instantly share code, notes, and snippets.

# nickihastings/symmetric-difference.js

Last active Apr 6, 2018
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 = {…
 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]);