So i am practicing algorithms(javascript), and i come across this challenge, where we have to filter an array, remove the following elements:
false, NaN, undefined, "", null, 0
My code seems to have problems with strings and chars, it failed these tests.
-bouncer([7, "ate", "", false, 9]) should return [7, "ate", 9] (returned [7, 9])
-bouncer(["a", "b", "c"]) should return ["a", "b", "c"] (returned [])
function bouncer(arr) {
return arr.filter(function(element)
{
if (element != false && !isNaN(element) && element != null && element != "" && element != undefined)
{return element;}
}
);
}
I would love a simple explanation of the concept i am missing
function bouncer(arr) {
return arr.filter(function(element) {
if (element) {
return element;
}
}
);
}
Here is the answer for you.
Beside the given coercion propblem with !=
instead of !==
, you could filter by using Boolean
as callback, which returns truthy elements.
function bouncer(arr) { return arr.filter(Boolean); } console.log(bouncer([7, "ate", "", false, 9])); // [7, "ate", 9] console.log(bouncer(["a", "b", "c"])); // ["a", "b", "c"]
The below code works for all the conditions. Please have a look at it.
function bouncer(arr) {
return arr.filter(function(element) {
if (element && element.trim().length > 0 && element != "NaN") {
return element;
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.