JS for loop loops once
New to JS and coding. First of all. I know that there are many similar questions, however, I read most of them and was unable to find an answer to my problem. I have put as much effort as I can, to create the best possible question.
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 loggin i to the console to see how many times it's iterating.
Again, if you find that my question needs fixing, please let me know instead of downvoting or closing it. I have spent two days trying to accomplish this task.
Link to the REPL: https://repl.it/@Otho01/Variables#index.js
from Recent Questions - Stack Overflow https://ift.tt/3cfTDpg
https://ift.tt/eA8V8J
Comments
Post a Comment