function bouncer(arr) {
// Don\'t show a false ID to this bouncer.
function a(b) {
if(b !== false) {
return b;
}
}
arr = arr.filte
Your function acts is it does because JavaScript values in boolean comparisons are "truthy" or "falsey". Non-booleans are coerced to a boolean value when used in a boolean context (comparisons, if statements, etc.)
If I understand your intent, you can modify your function to get your expected output like this:
function bouncer(arr) {
// Don't show a false ID to this bouncer.
function a(b) {
if(typeof(b) === 'boolean' && !b) {
return new Boolean(b);
}
}
arr = arr.filter(a);
return arr;
}
bouncer([7, 'ate', '', false, 9, true]);
Apparently .filter() was introduced in ES5.
This definitely helped me wrap my mind around what's going on here. Hope it helps!
Essentially, writing:
arr.filter(Boolean)
is the same as writing:
arr.filter( function(x) { return Boolean(x); });
since Boolean() is also a function that returns truthy when true and falsy when false!
Example:
var a = [1, 2, "b", 0, {}, "", NaN, 3, undefined, null, 5];
var b = a.filter(Boolean); // [1, 2, "b", {}, 3, 5];
Source: here.
I was solving a similar problem and came up with this:
function bouncer(arr) {
return arr.filter(Boolean);
}
bouncer([7, 'ate', '', false, 9]);
// returns ['7','ate','9']
It's because you return the value. The filter function should return true or false like this:
function bouncer(arr) {
arr = arr.filter(function(x) { console.log(x === true)
if(x !== false) {
return true;
}
});
return arr;
}
or shorter:
function bouncer(arr) {
return arr.filter(function(x) { console.log(x === true)
return x !== false;
});
}
simplest way to do it :
function bouncer(arr) {
return arr.filter(x => !!x);
}
I came across this exercise and was playing about with it somewhat. It ended up helping me understand it a bit better, so if you may I will add a bit of clarity to this bouncer function.
function bouncerOne(array){
let truthy = array.filter(x => x);
// This takes the .filter() and applies the anon function where it takes
// the value and returns the positive value. All values that are not Falsy including
// objects and functions would return True.
console.log("The Truth is:", truthy);//this Outputs the result to the console.
let falsy = array.filter(x => !x);
//This takes the .filer() and applies the
//annon function where it takes the value and only returns items that ARE NOT True.
//So Falsy Values are taken.
console.log("The Falsy Values are",falsy);
//The annon function of (x => x) & (x => !x)
// really makes use of the strict equality power of JavaScript.
// Where simple conditional test can be carried out.
};
console.log(bouncerOne([7, "ate", "", false, 9,null,42,"Bingo",undefined,NaN]));
//Returns: The Truth is: [ 7, 'ate', 9, 42, 'Bingo' ]
//The Falsy Values are [ '', false, null, undefined, NaN ]