Just wondering why my code doesn’t work.
Challenge is to remove any falsy values from an array. After peeping the hints I realize my solution is a little convoluted but I’m not sure why it doesn’t still work.
function bouncer(arr) {
let falsyArray = [false, null, 0, "", undefined, NaN];
for (let i = 0; i < arr.length; i++) {
if (falsyArray.indexOf(arr[i]) >= 0) {
arr.splice(i, 1);
}
}
return arr;
}
bouncer([7, "ate", "", false, 9]);
//The output is [ 7, 'ate', false, 9 ]
I created an array, falsyArray
of all the falsy values
I then iterate through each value of arr
, checking whether each value corresponds to any of the falsy values stored in falsyArray
- if there is a match, that value is removed from arr
using splice()
It looks like it only finds the first match, in this case the empty string ""
, deletes that and returns.
I know indexOf()
only finds the first match and returns, but I would have thought since it is utilized in the condition of an if
statement nested within a for
loop that the for
loop would still iterate through each value of arr
.
Is using indexOf()
the reason the for
loop stops iterating through arr
after finding the first match?
**Your browser information:**
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36
Challenge: Falsy Bouncer
Link to the challenge: