Say you have two arrays (pseudo-code):
arrayA = [ "a", "b", "c", "d" ];
arrayB = [ "b", "c", "d", "e" ];
Is it possible to find unique items to arrayA (arrayA.a), common items (b, c, d), and unique items to arrayB (arrayB.e) using only two loops in a nested format?
We can determine the first two objectives as such:
// Loop over arrayA
for (itemA in arrayA) {
// Loop over arrayB
for (itemB in arrayB) {
// Assume that arrayA.itemA does not exist in arrayB by default
exists = false;
// Check for matching arrayA.itemA in arrayB
if (itemA == itemB) {
// If true set exists variable and break the loop
exists = true;
break;
}
}
// Tells us if an item is common
if (exists) {
// Do something
}
// The additional condition we need to determine (item is unique to array b)
else if () {}
// Tells us if the item is unique to arrayA
else {
// Do something else
}
}
Question: Can we go a step further and determine the third condition (an item is unique to arrayB)? The trick is to be able to act on the third condition in the iteration of the first loop.
The loops can be in any format (do while, do, for, for in) and in any combination.
The second condition (item is unique to array b) will always be false, since you are iterating through items in A at that point. However, to answer your first question of building the 3 arrays with 2 loops in a nested format, here’s what I would do:
Note You could argue that copying
itemAanditemBis iterating through them. The only way I see around this is if you don’t care about keeping the initial array values and the values are unique, in which case you can usearrayAandarrayBin place ofuniqueAanduniqueBrespectively.