Skip to main content

Bonfire: Falsy Bouncer – Best Solution

By October 5, 2015Blog, Free Code Camp
Free Code Camp Bonfire: Bouncer

As always, my goal with these challenges is to make a clean solution that is either the most optimized code that can be written, or a solution that exemplifies some valuable coding principle.

The goal of this challenge is to remove all falsy values from an array. The suggested method was Array.filter().

Best Solution

function bouncer(arr) {
    arr = arr.filter(function (value) {
        if (!value) return;
        return value;
    });
    return arr;
}

bouncer([7, "ate", "", false, 9], "");

And here’s a CodePen with my solution in action: http://codepen.io/allurewebsolutions/pen/KdmVNb

Code Breakdown

From Mozilla: The filter() method creates a new array with all elements that pass the test implemented by the provided function.

The filter() method always requires some type of test inside of the parenthesis. In my solution, I wrote a function inside the filter() method that tests if a value is returned. The way we run this test is by asking if a value exists: !value – where value is one of the elements from arr being passed in. If a value does not exist for that element in the array (NULL, “”, false, NaN, false) then nothing is returned. You can see in the code nothing is following return. Otherwise, we return the value itself.

The filter function is smart and knows automatically to test for each element in the array individually. This is why we didn’t have to split the array and run a loop.

Alternative Solution

function bouncer(arr) {

    function test(value) {
        return Boolean(value);
    }

    return arr.filter(test);
}

bouncer([7, 'ate', '', false, 9]);

In this alternative solution, we write a function for testing if each element in the array arr exists or is otherwise NULL/NaN/false/””. If the value exists, the value is returned. If the value is Null, then nothing is returned.

The reason the final solution is written as is to show how we can write a function directly inside a method, instead of writing a function separately and just calling it inside the method. This isn’t necessarily the best practice in all coding scenarios, but it does exemplify the possibility of doing something like this.

Discussion

I would love to hear others’ solutions and discover better and cooler ways to solve these challenges. Please comment with your questions, suggestions, or anything you would like.

If you found my solution useful or learned something new from this blog post, please feel free add kudos inside the main chat of Free Code Camp: Thanks @allurewebsolutions

allure

Author allure

More posts by allure

Join the discussion 2 Comments

Leave a Reply

Designed by

best down free | web phu nu so | toc dep 2017