When working with a for
loop, the final expression that occurs, such as i++
in this case, will always be executed after the loop body. This means that regardless of the input array, the value of i
will be reset to 0
only at the beginning of the first iteration:
function bouncer(arr) {
for (let i = 0; i < arr.length; i++) {
console.log('i:', i);
if (!arr[i]) {
arr.splice(i, 1);
i = 0;
}
}
console.log(arr);
}
console.log(bouncer([false, null, 0, NaN, undefined, ""]));
To address this, you could reset i
to -1
instead, causing it to become 0
again at the start of the next loop iteration:
function bouncer(arr) {
for (let i = 0; i < arr.length; i++) {
console.log('i:', i);
if (!arr[i]) {
arr.splice(i, 1);
i = -1;
}
}
console.log(arr);
}
console.log(bouncer([false, null, 0, NaN, undefined, ""]));
Alternatively, you can simplify the logic by using .filter
instead. The .filter
method provides a more straightforward solution:
const bouncer = arr => arr.filter(Boolean);
console.log(bouncer([false, null, 0, NaN, undefined, ""]));