Finding matches between multiple JavaScript Arrays

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/

Leave a Comment