如何在数组列表中找到公共元素?

Vic*_*nak 1 javascript arrays

a = [1, 2, 3, 4, 5]
b = [1, 3, 6, 4, 5, 9]
c = [5, 4, 7, 9]
d = [1, 7, 5, 6, 9, 4]
e = [4, 3, 5, 7, 1]
f = [...]
.
.
(n = [n,n,n])
Run Code Online (Sandbox Code Playgroud)

对于许多情况中的一种,我们有 5 个变量,从ae,我们希望从这 5 个数组中获取交集元素,而不必为每种情况编写嵌套的 for..loop。

请提出这个问题的理想解决方案。

the*_*eye 5

首先找到第一个和第二个数组之间的公共元素,然后找到前一组公共元素和第三个数组之间的公共元素,依此类推。

var listOfArrays = [a, b, c, d, e, ...];
var commons = listOfArrays.slice(1).reduce(function(result, currentArray) {
    return currentArray.filter(function(currentItem) {
        return result.indexOf(currentItem) !== -1;
    });
}, listOfArrays[0]);
Run Code Online (Sandbox Code Playgroud)

这里,

currentArray.filter(function(currentItem) {...});
Run Code Online (Sandbox Code Playgroud)

是负责查找两个数组之间的公共元素的函数,result并且currentArray

我们使用Array.prototype.reduce传递给它的函数返回的值将在下一次迭代中反馈给同一个函数的地方。因此,我们继续将上一次迭代中的公共元素提供给下一次迭代。