Unraveling the nested loop — JavaScript

Raq Robinson
4 min readJul 17, 2020

Have you ever stumbled upon an algorithm problem and realized that a possible solution is a nested loop and wondered — wait where do I start the second iteration from again???

If this is you right now…

Don’t worry — me too!!

Let’s set this iterator straight!! Working with the below example:

let animals = ["duck", "pig", "chicken", "cow"]

To obtain all possible pair combinations of the ‘animals’ array we could use the following:

function unravel(arr){
for( let i=0; i< arr.length; i++){
for(let j=0; j< arr.length; j++){
console.log(arr[i], arr[j])
}
}
}
unravel(animals)

In this case the inner loop iterates for every single iteration of the outer for loop and yields sixteen pairs as follows:

input: animals = ["duck", "pig", "chicken", "cow"]=>          arr[i]     arr[j]         i j
duck duck 0 0
duck pig 0 1
duck chicken 0 2
duck cow 0 3
pig…

--

--