简体   繁体   English

foreach里面的foreach js

[英]Foreach inside foreach js

Trying to solve this problem and I don't know where my mistake is!试图解决这个问题,我不知道我的错误在哪里!

 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'

The problem was with how you were modeling the data.问题在于您如何对数据进行建模。 The parameter passed in should be an array of two arrays of integers, you had an array of two strings.传入的参数应该是一个由两个整数组成的 arrays 组成的数组,你有一个由两个字符串组成的数组。 If you have to work with an array of two strings, you have to extract the two strings and then use String.split() to convert them into arrays.如果您必须处理包含两个字符串的数组,则必须提取这两个字符串,然后使用 String.split() 将它们转换为 arrays。

 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)

You have various mistakes, including not splitting the string into an array, unnecessarily wrapping it in an array, and not returning your finalArr .您有各种错误,包括未将字符串拆分为数组、不必要地将其包装在数组中,以及未返回您的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;
}

Alternatively, use a faster solution with sets:或者,对集合使用更快的解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM