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

How can I find the common elements in a list of arrays?

本文关键字:元素 数组 列表      更新时间:2023-09-26
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])

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

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

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

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]);

这里

currentArray.filter(function(currentItem) {...});

是负责查找两个数组之间的公共元素的函数,resultcurrentArray

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

这是非Mr.Fancy-Pants版本的:)

function findIntersection() {
    // turns the list of arguments into an array
    var args = Array.prototype.slice.call(arguments);
    // concatenate all the arrays
    var all = args.reduce(function (a, b) { return a.concat(b); });
    // use the temporary object to store the number of times a
    // number appears
    for (var i = 0, obj = {}, l = all.length; i < l; i++) {
        var key = all[i];
        if (!obj[key]) obj[key] = 0;
        obj[key]++;
    }
    // return those numbers that have a value matching the number
    // of arguments passed into the function
    return Object.keys(obj).filter(function (el) {
        return obj[el] === args.length;
    }).map(Number);
}
findIntersection(a,b,c,d,e); // [ "4", "5" ]

演示