Tell us what’s happening:
My code is removing any truthy values that occur after a falsy value is present in the array, and I don’t understand why. For example, bouncer([7, “ate”, “”, false, 9]) returns 7, ate.
I figured out another way to solve this challenge by creating a new array and pushing truthy values into it, but I want to understand why this code doesn’t work. Any help is appreciated!
Your code so far
function bouncer(arr) {
// Don't show a false ID to this bouncer.
for (let i = 0; i < arr.length; i++) {
if (!!arr[i] === false) {
arr.splice(i);
i--;
}
}
return arr;
}
bouncer([7, "ate", "", false, 9]);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/falsy-bouncer
You are looping over arr while at the same time you are removing elements.
Consider what that does to arr.length and arr[i]
You might do better to have an empty array that you add truthy items to.
1 Like
My attempt to compensate for that was the “i–” within the if statement, and I guess I’m just not understanding why that doesn’t fix it. I think I get what you’re saying - that if you remove arr[2] (in this case “”), then arr[3] takes its place (in this case, arr[2] becomes false). I feel like decrementing i should account for that change, and should also keep i from exceeding the new arr.length. Is there something I’m missing in my understanding?
I did figure out how to do it using an empty array, but I’m just nitpicking and trying to understand where I went wrong in this code so I know better for the future.
Thanks for your help!
I took a second look at your function. Actually you were very close to a working solution.
arr.splice(i);
This deletes from index i to end of array. (When number of elements to remove is not specified it takes all to end of array.)
arr.splice(i,1);
This would work because it only removes one element and your i--
would have reset the index to compensate for the removed element. That is a tad hacky but clever all the same.
Here’s the syntax section on splice on MDN
1 Like
Yep, that was the issue! Deleting the rest of the array would definitely keep the code from returning the rest of the truthy values. It always ends up being a minor detail that keeps the entire code from working.
Thanks so much for all your help, I really appreciate it!