The filter() method creates a new array with all elements that pass the test implemented by the provided function.
so in this case x=>x is same as an if statement.
//Any thing that is not 0, false, null, undefined, empty string, or NaN, will pass the test.
const value = 123;
if(value) {
console.log(true);
} else {
console.log(false);
}
Based on your code, you won’t get the result of [null]. It should be [NaN].
You didn’t put in the check of NaN in your code. But even if you did the way above, it won’t work either. The reason is that NaN is not equal to NaN, at any point. So you can’t use == or === for this challenge.
What you end up doing now is just list all falsy value literally, see here
As callback function of filter method is a boolean, you could simply convert the value to a boolean. Either one works:
function bouncer(arr) {
return arr.filter(value => Boolean(value));
}
function bouncer(arr) {
return arr.filter(value => value);
}
Or simply
function bouncer(arr) {
return arr.filter(Boolean)
}
Note that “Boolean” is a constructor that takes in one parameter, so the first parameter in the callback function (i.e. the value) is passed into “Boolean” constructor. Hence you get the same result.
Hi, guys i have the same problem here, why the code below doesn’t work?
function bouncer(arr) {
// Don’t show a false ID to this bouncer.
var falsy = [false, null, 0, NaN, undefined, “”];
for (let i = 0; i<arr.length;i++){
if (falsy.indexOf(arr[i]) >= 0){
arr.splice(i,1);
}
}
return arr;
}
it’s because indexOf uses strict equality (===) to find the element but unforturnately that doesn’t work with NaN.
If you can believe it NaN === NaN is false in the JavaScript world. To do an explicit test for NaN you have to use Number.isNaN(). But on the other hand the if-condition implicitly tests whatever expression is in it for truthyness and that makes things much easier.