Skip to content

Instantly share code, notes, and snippets.

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 nirajkrz/0a2cb778715558ebe06c to your computer and use it in GitHub Desktop.
Save nirajkrz/0a2cb778715558ebe06c to your computer and use it in GitHub Desktop.
http://www.freecodecamp.com/nirajkrz 's solution for Bonfire: Symmetric Difference
// Bonfire: Symmetric Difference
// Author: @nirajkrz
// Challenge: http://www.freecodecamp.com/challenges/bonfire-symmetric-difference
// Learn to Code at Free Code Camp (www.freecodecamp.com)
function sym() {
// Convert the argument object into a proper array
var args = Array.prototype.slice.call(arguments);
// Return the symmetric difference of 2 arrays
var getDiff = function(arr1, arr2) {
// Returns items in arr1 that don't exist in arr2
function filterFunction(arr1, arr2) {
return arr1.filter(function(item) {
return arr2.indexOf(item) === -1;
});
}
// Run filter function on each array against the other then get unique values
return filterFunction(arr1, arr2)
.concat(filterFunction(arr2, arr1))
.filter(function(item, idx, arr) {
// Keep any items that are unique - the index of the current item === index of the first occurrence in the array
return arr.indexOf(item) === idx;
});
};
// Reduce all arguments getting the difference of them
return args.reduce(getDiff, []);
}
sym([1, 2, 3], [5, 2, 1, 4]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment