Given two arrays:
const a = ['one', 'two', 'three', 'four', 'five']
const b = [1, 2, 3, 4, 5]
How can pair up every value in a
with every value in b
? By iterating over a
in one loop (the outer), and then iterating over b
in a nested loop (the inner).
const c = []
for (let m of a) { // one iteration in total
for (let n of b) { // one iteration per outer value
c.push([m, n])
}
}
Now we can log out the array, c
to reveal all the pairs that are possible…
console.log(c)
[
['one', 1], ['one', 2], ['one', 3], ['one', 4], ['one', 5],
['two', 1], ['two', 2], ['two', 3], ['two', 4], ['two', 5],
['three', 1], ['three', 2], ['three', 3], ['three', 4], ['three', 5],
['four', 1], ['four', 2], ['four', 3], ['four', 4], ['four', 5],
['five', 1], ['five', 2], ['five', 3], ['five', 4], ['five', 5]
]
Notice how many pairs there are? Five values in a
paired with the five values in b
gives us twenty-five pairs. This points to multiplication…
a.length * b.length => 25
The inner loop runs once through for each value in the outer loop, for a total of 5 iterations.