Since i´m a beginner o coding, my logic went to use primitive Boolean´s to compare the item´s
filtered, but this was before I have read the Boolean Object reference, you see is that
like its written there,
"The value passed as the first parameter is converted to a Boolean value if necessary. If value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false. All other values, including any object or the string "false", create an object with an initial value of true."
So the logic since filter returns the value if it´s true or false, you should return values if
they are true.
Also, I didn´t learn everything about the filter method, for what I have researched, I have got
a bit more of information, that I will try to explain here.´
redefining the method (it already exists, is just for understanding)
the filter method accepts a function called
a predicate, that is a function that receives
a value and returns true or false.
The var results is an empty array where the results will be pushed with the push method.
The we use a forEach method with this, (this, in this context is applied to the array prototype ,this means that you will have the filter method available on every array that you define, with
the sintax of array.method(args) ins this case array.filter(args))
some resources
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype
Now we will run an operation in every item on the the array, with the forEach method, now we will apply the predicate function to itch item of the array and if it returns true, will add it to the results.
Array.prototype.filter = function(predicate){
var results = [];
this.forEach(function(item) {
if (predicate(item)) {
results.push(item);
}
});
};
//-------------------------------Correct Solution---------------------------
function bouncer (arrToFilter){
return arrToFilter.filter(Boolean);
}
//----------Code without the filter method---------
function bouncerNoFilterMethod(arrToFilter){
var results = [];
arrToFilter.forEach(function(arrToFilter){
if(arrToFilter){
results.push(arrToFilter);
}
});
return results;
}
console.log(bouncerNoFilterMethod([7, "ate", "", false, 9]));
console.log(bouncerNoFilterMethod(["a", "b", "c"]));
console.log(bouncerNoFilterMethod([false, null, 0, NaN, undefined, ""]));
console.log(bouncerNoFilterMethod([1, null, NaN, 2, undefined]));
console.log(bouncer([7, "ate", "", false, 9]));
console.log(bouncer(["a", "b", "c"]));
console.log(bouncer([false, null, 0, NaN, undefined, ""]));
console.log(bouncer([1, null, NaN, 2, undefined]));
Hope this helps to understand, the method, and the first thing that was not understanding was the part of passing the function, the predicate to the method, if I have mistakes here please suggest corrections.