0

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")
            }


      }

      }

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?

WilliamG
  • 451
  • 1
  • 8
  • 16

2 Answers2

3

You could use a hash table and a linear approach by iterating first arrayB and collect the name property and then iterate over arrayA and check if the id is in arrayB with the hash table. Add the information to arrayB if not exist.

var arrayA = [{ id: 1 }, { id: 3 }, { id: 4 }, { id: 6 }, { id: 7 }, { id: 9 }, { id: 12 }, { id: 35 }, { id: 22 }, { id: 11 }, { id: 34 }, { id: 90 }, { id: 2 }],
    arrayB = [{ name: 1 }, { name: 7 }, { name: 8 }, { name: 19 }, { name: 25 }, { name: 41 }, { name: 35 }, ],
    hashB = Object.create(null);

arrayB.forEach(function (b) {
    hashB[b.name] = true;
});

arrayA.forEach(function (a) {
    if (!hashB[a.id]) {
        arrayB.push({ name: a.id });
        hashB[a.id] = true;
    }
});

console.log(arrayB);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

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")
         }
   }
Ankur Agarwal
  • 286
  • 1
  • 5