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)
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)
Share Improve this question edited Sep 9, 2017 at 11:08 jc_mc asked Sep 9, 2017 at 11:05 jc_mcjc_mc 1771 gold badge1 silver badge9 bronze badges 2- Nested forEachs are working, yes. – Jonas Wilms Commented Sep 9, 2017 at 11:11
- yes it works, you can nest as many forEachs as you want – C.Unbay Commented Sep 9, 2017 at 11:12
2 Answers
Reset to default 4For 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 pletely 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)
}
}
}
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 plexity 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);
}
});
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744368548a4570829.html
评论列表(0条)