我需要制作一个实用程序来检查 3 个数组的交集。
这是我在 JS 中的实现:

function intersection(array1, array2, array3) {
    let intermediateList = [];
    let intermediateList2 = [];
    for (let i = 0; i < array1.length; i++) {
        if (!(array2.indexOf(array1[i]) == -1)) {
            intermediateList.push(array1[i]);
        }
        for (let j = 0; j < intermediateList.length; j++) {
            if (!(intermediateList.indexOf(array3[j]) == -1)) {
                intermediateList2.push(intermediateList[i]);
            }
        }
    }
    let endList = [ ...intermediateList, ...intermediateList2];
    return endList;
}

intersection([5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20])
//  [5, 15] /--> fine

intersection([5, 10, 15, 20, 40, 32], [32, 15, 88, 1, 5, 7, 40], [1, 10, 15, 5, 20, 40, 32])
// [5, 15, 40, 32, undefined, undefined, undefined] /--> can someone spot why do I get those undefined values?

您将如何使用 reduce 实现这一点?

最佳答案

您的函数有一个嵌套的 for 循环,每次运行外循环时都会迭代中间列表。然后你用索引 i 而不是索引 j 推送一个值,但这应该只在两个 for 循环不是嵌套而是链接时才有效。

function intersection(array1, array2, array3) {
    let intermediateList = [];
    let intermediateList2 = [];
    for (let i = 0; i < array1.length; i++) {
        if (array2.indexOf(array1[i]) !== -1) {
            intermediateList.push(array1[i]);
        }
    }
    for (let j = 0; j < intermediateList.length; j++) {
        if (array3.indexOf(intermediateList[j]) !== -1) {
            intermediateList2.push(intermediateList[j]);
        }
    }
    return intermediateList2;
}

console.log(intersection([5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]));
console.log(intersection([5, 10, 15, 20, 40, 32], [32, 15, 88, 1, 5, 7, 40], [1, 10, 15, 5, 20, 40, 32]));
.as-console-wrapper { max-height: 100% !important; top: 0; }


您可以减少参数并返回具有公共(public)值的单个数组。

const intersection = (...array) => array.reduce((a, b) => a.filter(v => b.includes(v)));

console.log(intersection([5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]));
console.log(intersection([5, 10, 15, 20, 40, 32], [32, 15, 88, 1, 5, 7, 40], [1, 10, 15, 5, 20, 40, 32]));

关于javascript - JavaScript 中获取三个数组的交集,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51621141/

10-12 03:03