jc_mc
jc_mc

Reputation: 177

Nesting foreach in foreach

I have array "A" holding values [a,b] and array "B" holding values [b,c]; I want to use each row of array "A" as a logical filter and cycle trough every row of "B";

What I do is:

A.foreach(function(e) { // pick row n from A 
    B.foreach(function(x) { // run trough B
        if (e.value === x.value) { // business logic
            console.log(result);
        }
    });
});

Question - is this an acceptable approach (nesting foreach in another foreach)

Upvotes: 1

Views: 11330

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138257

For primitives ( and object references):

const result = A.filter( el => B.includes(el));

For object key equality:

const result = A.filter( 
  el => B.some(
    el2 => el.value === el2.value
  )
);

Nested forEachs are completely valid, however in that case i would prefer simple for loops as theyre breakable:

 for(const el of A){
  for(const el2 of B){
    if(el.value === el2.value){
      alert("found it");
      break;//O(n/2) instead of O(n)
    }
  }
}

Upvotes: 4

Kunvar Singh
Kunvar Singh

Reputation: 1885

You may try for this:

And ofCourse this is an acceptable approach for writting forech inside foreach, but when data is too longer then its getting slow, and its complexity will be O(n2).

var A=['a','b'];
var B=['b','c'];
A.forEach(function(e) { // pick row n from A
    B.forEach(function(x) { // run trough B
        if (e.value === x.value) { // business logic
            console.log(x.value);
        }
    });
});

Upvotes: 0

Related Questions