Skip to content

Instantly share code, notes, and snippets.

@obiora22
Created April 30, 2017 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save obiora22/94e4ed8b01460c106ee44718c696c139 to your computer and use it in GitHub Desktop.
Save obiora22/94e4ed8b01460c106ee44718c696c139 to your computer and use it in GitHub Desktop.
Finding the symmetric difference between 2 arrays
function sym () {
var args_array = Array.prototype.slice.call(arguments);
var sym_difference;
// function that will select elements that are
// either in array A or array B
// Note that the symmetric difference between 3 sets includes any element present in all 3
function symDiff (array1, array2) {
// This will hold elements unique to either array
var result = [];
array1.forEach(function (elem) {
if (array2.indexOf(elem) < 0 && result.indexOf(elem) < 0) {
result.push(elem);
}
});
array2.forEach(function (elem) {
if (array1.indexOf(elem) < 0 && result.indexOf(elem) < 0) {
result.push(elem);
}
});
return result;
}
sym_difference = args_array.reduce(symDiff);
return sym_difference;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment