DEV Community

NJOKU SAMSON EBERE
NJOKU SAMSON EBERE

Posted on • Updated on

Algorithm 202: Falsy Bouncer in 4 Ways

A falsy bouncer algorithm is a step by step approach to removing all false or falsy values usually from an array. Falsy values includes: false, null, undefined, 0, NaN, and "".


falsyBouncer([undefined, 1, 0, 60000, null, NaN, '', "njoku Samson"])
// [ 1, 60000, 'njoku Samson' ]

Enter fullscreen mode Exit fullscreen mode

Do you think this is achievable? How can this be done?

Let me share 4 ways to bounce falsy values from an array.

Prerequisite

This article assumes that you have basic understanding of javascript's array methods.

Let's bounce falsy values from an array using:

  • for...of...loop, push()
      function falsyBouncer(array) {
        let sanitizedArray = [];

        for (element of array) {
          element ? sanitizedArray.push(element) : sanitizedArray;
        }

        return sanitizedArray;
      }
Enter fullscreen mode Exit fullscreen mode
  • forEach...loop, includes(), push()
      function falsyBouncer(array) {
        let falsyValues = [false, null, undefined, 0, NaN, ""];
        let sanitizedArray = [];

        array.forEach(element => {
          !falsyValues.includes(element)
            ? sanitizedArray.push(element)
            : sanitizedArray;
        });

        return sanitizedArray;
      }
Enter fullscreen mode Exit fullscreen mode
  • filter()
      function falsyBouncer(array) {
        let sanitizedArray = array.filter(element => Boolean(element));

        return sanitizedArray;
      }
Enter fullscreen mode Exit fullscreen mode
  • reduce()
      function falsyBouncer(array) {
        let sanitizedArray = [];

        sanitizedArray = array.reduce((acc, element) => {
          if (Boolean(element)) {
            return [...acc, element];
          } else {
            return acc;
          }
        }, []);

        return sanitizedArray;
      }
Enter fullscreen mode Exit fullscreen mode

Conclusion

There are many ways to solve problems programmatically. I will love to know other ways you solved yours in the comment section.

If you have questions, comments or suggestions, please drop them in the comment section.

Up Next: Algorithm 202: Where I Belong in 3 Ways

You can also follow and message me on social media platforms.

Twitter | LinkedIn | Github

Thank You For Your Time.

Top comments (2)

Collapse
 
zenulabidin profile image
Ali Sherief • Edited

I think that the third way of implementing a falsy bouncer is the easiest and shortest way. It doesn't get simpler than applying reduce with an arrow function.

Collapse
 
ebereplenty profile image
NJOKU SAMSON EBERE

Thank you Ali for taking your time to read through.

The idea was just to show different way to solving one problem but in no particular order.