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:
function order(words) { let sp = words.split(" "); // Array to split string let pos = 1; //variable to store number 1 to find in string let arr = []; //New array to push into, since trying to move values in same array wasn' tworking. for (let i = 0; i < sp.length; i++) { if (sp[i].includes(pos)) { arr.push(sp[i]); pos = pos + 1; } console.log(i); } return arr; } order("is2 Thi1s T4est 3a");
When I execute the above code, it returns:
0 1 2 3 [ 'Thi1s' ]
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:
function order(words){ let sp = words.split(" "); let arr = []; for (let pos = 1; pos <= sp.length; pos++) { for (let i = 0; i < sp.length; i++) { if (sp[i].includes(pos)) { arr.push(sp[i]) } } } return arr; } order("is2 Thi1s T4est 3a");
The result of this code is [ 'Thi1s', 'is2', '3a', 'T4est' ]