浏览数组(A)中的所有项目,并检查其是否已经存在于另一个数组(B)中 [英] Look through every items in array(A) and check if it allready exsists in another array(B)

查看:79
本文介绍了浏览数组(A)中的所有项目,并检查其是否已经存在于另一个数组(B)中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组(arrayA& arrayB).我想检查arrayB中是否已经存在所有arrayA中的项目.如果不是,我想将其添加到arrayB(但这不是问题).在示例文件中,我只想console.log将项目添加到数组B.

I have two arrays(arrayA & arrayB). I want to check if any of the items in arrayA allready exists in arrayB. if it doesn't I want to add it to arrayB(but that's not the problem). In the exampel I just want to console.log that I'm adding the item to array B.

首先,我认为这是一个好主意:

First I thought this was a good idea:

 for(var i = 0; i < arrayA.length; i++){
        for (var j = 0; j < arrayB.length; j++) {
            if(body[i].id == res[j].name){
                console.log("The article allready exsists")
            }
            else{
                console.log("Adding item to arrayB")
            }


      }

      }

然后我意识到这并不是一个很好的方法,因为数组很大.同样,else语句将运行等于arrayA长度的次数.还有一个问题,因为这将是第一次运行arrayB的数组长度为零,甚至不会达到else语句.

Then I realised that this wasn't a verry good way to do it because the array's are pretty big. Also the else-statement will be ran the number of times equal to the length of arrayA. Also It's a problem because the first time this will run the array length of arrayB will be zero and wont even reach the else-statement.

他们还有其他方法可以达到我在这里想要做的事情吗?

Is their any other ways to achive what I'm trying to do here?

推荐答案

这可能会有所帮助.您不需要嵌套循环即可实现这一目标.

May be this could help. You donot need nested loops for achieving this.

 var arrayA = [1,2,3,4,5,6];
 var arrayB = [2,4,7,8];
 for(var i = 0; i < arrayA.length; i++){
       if(arrayB.indexOf(arrayA[i]) > -1){
            console.log("The article allready exsists");
         }
         else{
             console.log("Adding item to arrayB")
         }
   }

这篇关于浏览数组(A)中的所有项目,并检查其是否已经存在于另一个数组(B)中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆