Finding matches between multiple JavaScript Arrays
Assuming there is an array of arrays those we want to find the intersection of, a simplest single liner approach could be
var arr = [[0,1,2,3,4,5,6,7,8,9],[0,2,4,6,8],[4,5,6,7]],
int = arr.reduce((p,c) => p.filter(e => c.includes(e)));
document.write("<pre>" + JSON.stringify(int) + "</pre>");
var result = arrays.shift().filter(function(v) {
return arrays.every(function(a) {
return a.indexOf(v) !== -1;
});
});
DEMO: http://jsfiddle.net/nWjcp/2/
You could first sort the outer Array to get the shortest Array at the beginning...
arrays.sort(function(a, b) {
return a.length - b.length;
});
For completeness, here's a solution that deals with duplicates in the Arrays. It uses .reduce()
instead of .filter()
...
var result = arrays.shift().reduce(function(res, v) {
if (res.indexOf(v) === -1 && arrays.every(function(a) {
return a.indexOf(v) !== -1;
})) res.push(v);
return res;
}, []);
DEMO: http://jsfiddle.net/nWjcp/4/