I'm studying at freeCodeCamp, and currently learning basic algorithms. I'm doing the falsy bouncer exercise at which you need to remove all falsy values from the array. Sadly there was only the advanced answer for the task, that uses the filter() method. I've decided to make a basic one, but currently stuck.
function bouncer(arr) {
//*loops through array*
for (let i = 0; i < arr.length; i++) {
// *if there is a value that is falsy, delete that value from the array*
if (arr[i] == 0 || arr[i] == NaN || arr[i] == null || arr[i] == false || arr[i] == "" || arr[i] == undefined) {
delete arr[i];
}
}
return arr;
}
console.log(bouncer([7, "ate", "", false, 9]));
It returns:
7,ate,,,9.
The function, indeed removed the falsy values, but I'm left with those three periods(,,,). Is there a way to make this function to work more correct and to return truthy values without those periods, without losing the simplicity of the function? Appreciate your help.
delete only works on objects. filter will do what you want:
const arr = [7, "ate", "", false, 9]
console.log(arr.filter(x => x))
filter retains only those elements in the array for which the function returns true - here I use x => x because you only want truthy elements
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With