Given an array with different data types. I write a function to find those values which are false and return the array without the falsy values.
For example:
[7, "ate", "", false, 9] should return [7, "ate", 9].
This is my current code:
function bouncer(arr)
{
for (var i = 0; i < arr.length; i++)
{
if (Boolean(arr[i]) == false)
{
arr.splice(i, 1);
}
}
console.log(arr);
}
However, there is a problem:
I.)
In case of Input: bouncer([7, "ate", "", false, 9])
It returns: [ 7, 'ate', false, 9 ]
But it should return: [7, "ate", 9]
II.)
In case of input: `bouncer([false, null, 0, NaN, undefined, ""]);`
It returns: [ null, NaN, '' ]
But it should return: []
I don't understand why it returns the boolean false values like NaN or null. But it correctly splices off values like empty strings ("") or undefined.
And I also don't understand, why in the first case it returns false (which is not intended), but in the second case it does not returns false.
Thank you very much for clarification.