The Ultimate Guide to JavaScript Algorithms: Falsy Bouncer

Publikováno: 4.3.2019

Falsy bouncer? Just in case your mind's been pacing frantically trying to make sense of the title of this challenge, worry not! We’ll do that together.

A bouncer is a person em...

Celý článek

Falsy bouncer? Just in case your mind's been pacing frantically trying to make sense of the title of this challenge, worry not! We’ll do that together.

A bouncer is a person employed by a nightclub or similar establishment to prevent troublemakers and other unwanted from people entering or to eject them from the premises.

Yup! That big scary guy.

Now you’re wondering what this has to do with JavaScript. Well, in this challenge, we’ll be strengthening our array manipulation skills by writing a bouncing function that removes every falsy element from within an array.

What is a falsy value?

A falsy value is a value that is considered false when examined as a Boolean. Recall that a Boolean value could either be true or false. JavaScript uses type conversion to translate any value to true or false when required. Examples of falsy values are: false, null, undefined, 0, NaN, and "".

Isn’t this cool? We’get to create our own big scary guy. Having understood the context of this challenge, let’s dive right in.

You should already have your development environment setup for this course. Open the cloned repository and inside the Beginner folder, navigate to the falsyBouncer folder. Our work for this challenge will be done in here. Make sure to follow along in the index-START.js file.

The Challenge

Given an array, remove all falsy values from the array and return an array of only truthy values. E.g

falsyBouncer([1, 0, null, '', 5]) // should return [1,5]

Algorithmic Thinking

Basically, we are to write a function that accepts a parameter i.e an array from which falsy values are to be removed.

To achieve this, we must loop through the array and test each element within to see if they are truthy or falsy. The result of this evaluation is what determines whether they stay or go.

Let’s get codey, shall we?

Code Implementation

We will explore two(2) ways to solve this challenge below. They are:

  • Using a for…of loop
  • Using .filter()

Using a for…of loop

In this approach we use a for…of loop to access every element(value) within the array and then carry out a check to see if it is falsy.

function falsyBouncer(array) {
    let result =[]
    //loop through with each array value
    for (value of array){
    // push into result if truthy
        if(value){
            result.push(value)
        }
    }
    return result
}

Remember that the condition in an if statement evaluates to true or false. Thus, using an if statement, we check if the value evaluates to true or false. If it evaluates to true, we push it into our final result array which is initially empty. If it evaluates to false however, the block of code doesn't get executed and we move on to the next value.

At the end of the iteration, result now contains all the truthy(non-falsy) values, and it is returned as such.

Using .filter()

The .filter() method is used to create a new array from an existing array. The new array only contains elements that pass a specified test or condition.

In the code snippet below, we use this to "filter" the received array and only return elements that evaluate to a truthy value.

function falsyBouncer(array) {
    return array.filter((value) =>{
      return Boolean(value)     })
}

We convert the values(elements) to their corresponding Boolean equivalent using the Boolean() function.

Recall that only the elements that pass the test(i.e evaluate to true) are returned by .filter() in the new array.

Thus, in the end we have an array containing only the truthy values from the received array and that is why we return it from the function as such.

Pretty straight forward solutions indeed! Let the testing begin!

Testing

Testing Correctness with Jest

You may run the tests for each solution above by executing the command below from your terminal:

npm run test falsyBouncer
  • Using a for…of loop

  • Using .filter()

Testing Performance with JSPerf

Follow this link to JSPerf in order to carry out the performance test for the solutions above. See the result in the screenshot below.

A pretty close one it is! From our performance test, we see that the for…of loop is the faster approach to solving this problem. However, the **.filter()** method is only approximately 5% slower.

Practical Application

This challenge is mostly encountered as an interview coding challenge. It is also a part of Freecodecamp's Algorithm Scripting challenges.

As in the previous challenge(link) we considered, these solutions may also enable us clean up our data-set for computation and visual representation in real world applications.

Conclusion

We have now successfully created our own bouncer algorithm. Our performance test has also revealed that a using a for…of loop is a more optimal solution than using the .filter() method. However, both do not vary by much performance-wise.

Further Reading

To gain a better understanding of the concepts highlighted in this challenge, you may use these links:

See you in the next one!✌????

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace