【问题标题】:Merging multiple arrays and get an array of common elements as output合并多个数组并得到一个公共元素数组作为输出
【发布时间】:2020-07-20 04:57:34
【问题描述】:

我正在尝试以角度合并 javascript/typescript 中的几个数组,我需要输出一个包含所有数组中的公共值的数组。 例如:

arrayOne = [34, 23, 80, 93, 48]
arrayTwo = [48, 29, 10, 79, 23]
arrayThree = [23, 89, 48, 20, 63]

输出:outputArr= [23, 48]

为了从 2 个数组中获取公共元素,我使用下一个数组中的元素过滤一个数组。

return this.arrayOne.filter(el => this.arrayTwo.includes(el));

如果我必须合并大量数组,我该如何有效地做到这一点......? 提前谢谢...

【问题讨论】:

标签: arrays typescript merge


【解决方案1】:

您可以使用多个Set 快速查找不同集合中的每个值。

const intersection = <T>(arrays: T[][]): T[] => {
    if (arrays.length == 0) return [];
    if (arrays.length == 1) return arrays[0];

    const sets = arrays.slice(1).map(array => new Set(array));

    const result = [];

    arrays[0].forEach(item => {
        if (sets.every(set => set.has(item))) {
            result.push(item);
        }
    });

    return result;
};

const arrayOne = [34, 23, 80, 93, 48];
const arrayTwo = [48, 29, 10, 79, 23];
const arrayThree = [23, 89, 48, 20, 63];

const result = intersection([arrayOne, arrayTwo, arrayThree]);

console.log(result);

【讨论】:

    【解决方案2】:

    一种方法是创建一个包含第一个数组元素的初始集合。然后遍历其他数组,将它们转换为集合并更新初始集合以保留相应的集合交集。

    const commonElements = function(arrays) {
        if (arrays.length == 0)
            return [];
        const intersection = new Set(arrays[0]);
        for (const array of arrays) {
            const set = new Set(array);
            for (x of intersection) {
                if (!set.has(x))
                    intersection.delete(x);
            }
        }
        return Array.from(intersection);
    };
    

    在问题中的示例数组上调用此函数:

    commonElements([
        [34, 23, 80, 93, 48],
        [48, 29, 10, 79, 23],
        [23, 89, 48, 20, 63]])
    

    返回:

    [23, 48]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-07
      • 2017-05-11
      • 2012-03-04
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多