Confusion with falsy bouncer

Tell us what’s happening:
Howdy folks! I’ve actually completed this challenge using the .filter() method.

However, I’m confused as to why my first solution didn’t work:

function bouncer(arr) {
for (let i = 0; i < arr.length; i++) {
  if (!arr[i]) {
    arr.splice(i, 1); // removes all falsy values except for false!!!
  }
}
return arr;
}
bouncer([true, 7, undefined, "ate", "", false, null, 9, NaN]);
// returns [ true, 7, 'ate', false, 9 ]

Particularly, as the following code does remove the value false from the array:

let arr = [true, 7, undefined, "ate", "", false, null, 9, NaN];

if (!arr[5]) arr.splice(5, 1);
console.log(arr); // [ true, 7, undefined, 'ate', '', null, 9, NaN ]

So, what’s actually going on here? Thanks!

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0.

Challenge: Falsy Bouncer

Link to the challenge:

Hello there.

You are removing items inside an array you are iterating through… So, your array is changing size:

let myArr = [2,3,4,5,6,7,8,9];
for (let i = 0; i < arr.length; i++) {
  if (i % 2 === 0) {
    arr.splice(i,1);
  }
}

First iteration: i == 0; arr.length == 8; arr[i] == 2;
Second iteration: i == 1; arr.length == 7; arr[i] == 4; It skipped 3!!

Can you see where this is going?

2 Likes

Yes, of course!!! I feel so stupid now!

Anyway, thanks for the help!