Foreach inside foreach js



试图解决这个问题,但我不知道我的错误在哪里!

function findIntersection(strArr) {
const arr1 =[strArr[0]];
const arr2 = [strArr[1]];
const finalArr =[];
arr1.forEach(e=>{arr2.forEach(element => {
if(element === e){
finalArr.push(e);
console.log(true)
}
})})
}
findIntersection(['1, 3, 4, 7, 13', '1, 2, 4, 13, 15']); // => '1,4,13'
findIntersection(['1, 3, 9, 10, 17, 18', '1, 4, 9, 10']); // => '1,9,10'

您有各种错误,包括没有将字符串拆分为数组、不必要地将其包装在数组中以及没有返回finalArr

function findIntersection(strArr) {
const arr1 = strArr[0].split(", ");
const arr2 = strArr[1].split(", ");
const finalArr = [];
arr1.forEach(el1 => {
arr2.forEach(el2 => {
if (el1 === el2) {
finalArr.push(el1);
}
});
});
return finalArr;
}

或者,使用更快的套装解决方案:

function findIntersection(strArr) {
const arr1 = new Set(strArr[0].split(", "));
const arr2 = strArr[1].split(", ");
return arr2.filter(el => arr1.has(el));
}

问题在于如何对数据建模。传入的参数应该是由两个整数数组组成的数组,您有一个由两个字符串组成的数组。如果必须使用两个字符串的数组,则必须提取这两个字符串,然后使用String.split((将它们转换为数组。

function findIntersection(strArr) {
const arr1 = strArr[0]
const arr2 = strArr[1]
const finalArr = [];

arr1.forEach(el1 => {
arr2.forEach(el2 => {
if (el2 === el1) {
finalArr.push(el1);
}
})
})
return finalArr
}
const res1 = findIntersection([[1, 3, 4, 7, 13], [1, 2, 4, 13, 15]]); // => '1,4,13'
const res2 = findIntersection([[1, 3, 9, 10, 17, 18], [1, 4, 9, 10]]); // => '1,9,10'
console.log(res1, res2)

最新更新