gpt4 book ai didi

javascript - 在 JavaScript 中获取三个数组的交集

转载 作者:行者123 更新时间:2023-11-29 10:28:48 29 4
gpt4 key购买 nike

我需要制作一个实用程序来检查 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 循环,每次运行外层循环时都会迭代 intermediateList。然后你推送一个索引为 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com