Tell us what’s happening:
I know that the following code solves this challenge very effectively, however I was first experimenting another way and I wanted to discuss that way and get some feedback as I have not been able to make it work. Please see the second code snippet below for the code I am trying as well as the debugging code I wrote to wrap my mind around what’s happening.
Solution that works
function bouncer(arr) {
// Don't show a false ID to this bouncer.
var truthy = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i]) {
truthy.push(arr[i]);
}
}
return truthy;
}
bouncer([7, "ate", "", false, 9]);
What I tried -
function bouncer(arr) {
for (var i = 0; i < arr.length; i++) {
if (!arr[i]) {
arr.splice(i, 1);
}
}
return arr;
}
bouncer([7, "ate", "", false, 9]);
I figure out the above was not working due to the index being changed everytime I splice and hence the values of i skips elements. Figure this out by doing below -
function bouncer(arr) {
var boolCollect = [];
for (var i = 0; i < arr.length; i++) {
console.log("inspecting: ", arr[i]);
if (!arr[i]) {
boolCollect.push(true);
} else { boolCollect.push(false); }
}
console.log(boolCollect);
return arr;
}
bouncer([7, "ate", "", false, 9]);
My question is, instead of filtering out the truthy values and making a new array as I am doing in the solution in the very first code snippet, is there a way to eliminate the falsy values from the same array and return. I have been going through the array methods documentation and haven’t been able to put it together yet.
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.170 Safari/537.36
.
Link to the challenge:
https://www.freecodecamp.org/challenges/falsy-bouncer