Skip to content

Instantly share code, notes, and snippets.

@sfoster
Created January 23, 2013 15:53
Show Gist options
  • Save sfoster/4608516 to your computer and use it in GitHub Desktop.
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.
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