Reputation: 171
So I am doing the FreeCodeCamp challenge "Remove all falsy values from an array."
I made a function, but for some reason it does not filter all the falsy values:
function bouncer(arr) {
function truthy(value) {
return value !== '' ||false || null || undefined || NaN ;
}
var filtered = arr.filter(truthy);
return filtered;
}
bouncer([7, "ate", "", false, 9]);
This should return
[7, "ate", 9],
but instead returns
[ 7, 'ate', false, 9 ]
If I switch the order of the function truthy, the returned values changes. For example moving the '',
function truthy(value) {
return value !== '' ||false || null || undefined || NaN ;
----->
return false || null || undefined || NaN || " ;
The new
false || null || undefined || NaN || " ; returns
[ 7, 'ate', '', 9 ]
Any idea what is going on??? Thanks!
Upvotes: 0
Views: 922
Reputation: 192517
In addition to AuxTaco's answer...
"All falsy values" include 0 as well.
You can shorten the filter expression a bit further, by using Boolean
as function:
function bouncer(arr) {
return arr.filter(Boolean);
}
console.log(bouncer([7, "ate", "", false, 9, 0, NaN, null, undefined]));
Upvotes: 1
Reputation: 5181
return value !== '' ||false || null || undefined || NaN ;
This does not do what you think it does. It's actually equivalent to
(((((value !== '') || false) || null) || undefined) || NaN)
When value !== ''
, as in most of your cases, this expression is true. You would actually need to check
value !== '' && value !== false && value !== null && value !== undefined && value !== NaN
But since these are all falsy anyway and Array.filter
only cares about truthiness and falsiness, you can replace your truthy
function with
function truthy(value) {
return value;
}
which isn't even worth breaking out three lines for:
var filtered = arr.filter(e => e);
Upvotes: 5
Reputation: 318
The problem is, your return statement, will always return true when the value is different than blank
function truthy(value) {
return value !== '' ||false || null || undefined || NaN ;
}
should be something like this
function truthy(value) {
falseValues = ['',false,null,undefined,NaN];
return !falseValues.contains(value);
}
Upvotes: -1