Forked from anonymous/bonfire-symmetric-difference.js
Created
December 8, 2015 21:10
-
-
Save nirajkrz/0a2cb778715558ebe06c to your computer and use it in GitHub Desktop.
http://www.freecodecamp.com/nirajkrz 's solution for Bonfire: Symmetric Difference
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
// 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