Created
April 30, 2017 17:07
-
-
Save obiora22/94e4ed8b01460c106ee44718c696c139 to your computer and use it in GitHub Desktop.
Finding the symmetric difference between 2 arrays
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 () { | |
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