Skip to content
Advertisement

JS for loop loops once

My problem is that I am trying to iterate over an array several times, however, my for loop will only iterate over the array once (Or so it seems to me) which causes the outcome to be wrong.

What I am trying to do is loop on this array: let arr = ["e5", "b2", "a1", "c3","d4"]; and grabbing the string based on its number to move it to the first, second, third… position in the array depending on that number.

My code does not throw any error, however, seems like it iterates only once, grabs "a1", moves it to position 0 in the array and that’s it. It doesn’t iterate again to grab b2 and move it to position 1 in the array.

Next I would like to show you my code:

JavaScript

When I execute the above code, it returns:

JavaScript

So as you can see, the result tells me that it iterates once, grabs "thi1s" and pushes it to the new array, however, it stops at that point and doesn´t do the other iterations or the rest of the pushing.

I am logging i to the console to see how many times it’s iterating.

Link to the REPL: https://repl.it/@Otho01/Variables#index.js

Advertisement

Answer

The algorithm provided only loops the array of words once. For what you stated your goal is to find the position of each word based on a number inside each word. There are several ways of solving this but I will explain an easy algorithm.

You can accomplish the desired result by creating a loop over the positions {1..N} and inside this loop another loop on the words {word1...wordN}. So for each position you will try to find what word belongs to that position. The following algorithm is one of many solution for this problem:

JavaScript

The result of this code is [ 'Thi1s', 'is2', '3a', 'T4est' ]

Advertisement