I was trying to solve this codewars question called "Your order, please". Our task is to to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.
Lets say given string is "is2 Thi1s T4est 3a" then expected result is "Thi1s is2 3a T4est".
So here is my code
let words = "is2 Thi1s T4est 3a";
let wordsArr = words.split(" ");
let result = [];
let r = /\d+/g;
let j = 1;
for (let i = 0; i < wordsArr.length; i++) {
if (wordsArr[i].match(r) == j) {
result.push(wordsArr[i]);
j++;
i = 0;
}
}
console.log(result.join(""));
It only returns Thi1s
.
I tried to write down the iterations of how I think it would work with this for loop.
iteration (i=0, j=1)
- 2==1? no then i++
iteration (i=1,j=1)
- 1==1? yes then push.result, j++, i=0
- result=[Thi1s]
- 1==1? yes then push.result, j++, i=0
iteration (i=0,j=2)
- 2==2? yes then push.result, j++, i=0
- result=[Thi1s, is2]
- 2==2? yes then push.result, j++, i=0
iteration (i=0,j=3)
- 2==3? no then i++;
iteration (i=1,j=3)
- 1==3? no then i++
iteration (i=2,j=3)
- 4==3? no then i++
iteration (i=3, j=3)
- 3==3? yes then push.result, j++ i=0
- result=[Thi1s, is2, 3a]
- 3==3? yes then push.result, j++ i=0
iteration (i=0,j=4)
- 2==4? no then i++;
iteration (i=1,j=4)
- 1==4? no then i++;
iteration (i=2,j=4)
- 4==4? yes then push.result, j++ i=0
- result=[Thi1s, is2, 3a, T4est]
- 4==4? yes then push.result, j++ i=0
Why is it not working the way I expected to work?