Created
January 23, 2013 15:53
-
-
Save sfoster/4608516 to your computer and use it in GitHub Desktop.
Array intersection: an array of values which occur in each of the passed arrays. Does the right thing with empty arrays.
This file contains hidden or 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
var palette1 = ("white,green,brown,blue,orange").split(','), | |
palette2 = ("cyan,orange,black,white").split(','), | |
palette3 = ("black,white,grey").split(','); | |
// given one or more arrays of values, | |
// return an array with only those values present in each | |
function intersection() { | |
var lists = Array.prototype.slice.call(arguments); | |
return lists.reduce(function(aCommon, aValues){ | |
var overlap = aValues.filter(function(val){ | |
return aCommon.indexOf(val) > -1; | |
}); | |
return overlap; | |
}, lists.shift()); | |
} | |
console.log('result: ', intersection(palette3, palette2, palette1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment