Making a simple function that takes an array, and returns the same array with the elements false, null, 0, "", undefined, and NaN removed from the array.
Here I leave several "situations" where it does not work (except the first one if it works) and below the result that each one gives.
function bouncer(arr) {
var filtered = arr.filter(function(value, index, arr){
return value != null ;
})
return filtered
}
bouncer([7, null, 9]);
//ELIMINA null correctamente
function bouncer(arr) {
var filtered = arr.filter(function(value, index, arr){
return value != null | "" ;
})
return filtered
}
bouncer([7, null, "", 9]);
// ELIMINA "" pero no null!
function bouncer(arr) {
var filtered = arr.filter(function(value, index, arr){
return value != NaN ;
})
return filtered
}
bouncer([7, NaN, 9]);
////No ELIMINA Nada!
function bouncer(arr) {
var filtered = arr.filter(function(value, index, arr){
return value != false ;
})
return filtered
}
bouncer([7, null, "", 9]);
//ELIMINA "" pero no null
When you do a comparison with
==
or!=
, Javascript first tries to convert the values to a common type. You can read this MDN article to understand the matter.Now, the values that you want to filter are just the values that JavaScript considers "falsy" . What does falsy mean exactly? Well, when you convert to type
boolean
, they will be transformed intofalse
.Something as simple as this would work:
because we are forcing the conversion from
value
to typeboolean
.Edit: there is a shorter way to achieve the same result:
You have a few bugs:
Comparisons don't work like that... and you're using the binary operator . Should be
Another, and this one you will like:
Nan
he is different from everything ... even himself !The last:
You already know: a promotion of types is carried out. Should be: