-2

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

Vishwad
  • 251
  • 3
  • 18

3 Answers3

1
function bouncer(arr) {
    return arr.filter(function(element) {
            if (element) {
                return element;
            }
        }
    );
}

Here is the answer for you.

Gautam
  • 815
  • 6
  • 15
0

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"]
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

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;
        }
    });
}
  • @vishwad - The code shared by Gautam doesn't check for 'NaN', so please keep a check for that as well in your code. Thanks! – Shrikant Potty Oct 09 '17 at 17:40