How to remove falsy values from an array in JavaScript

How to remove falsy values from an array in JavaScript

There are a lot of ways to remove elements from an array in JavaScript, but what’s the easiest way to remove all falsy values from an array? In order to answer that question we’ll take a close look at truthy versus falsy values and type coercion within the context of an algorithm scripting challenge.

There are a lot of ways to remove elements from an array in JavaScript, but what’s the easiest way to remove all falsy values from an array? In order to answer that question we’ll take a close look at truthy versus falsy values and type coercion within the context of an algorithm scripting challenge.


Algorithm instructions

Remove all falsy values from an array.
Falsy values in JavaScript are false, null, 0, "", undefined, and NaN.
Hint: Try converting each value to a Boolean.
function bouncer(arr) {
      return arr;
    }


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


Provided Test Cases

  • bouncer([7, "ate", "", false, 9])should return [7, "ate", 9].
  • bouncer(["a", "b", "c"])should return ["a", "b", "c"].
  • bouncer([false, null, 0, NaN, undefined, ""])should return [].
  • bouncer([1, null, NaN, 2, undefined])should return [1, 2].

Solution #1: .filter( ) and Boolean( )

PEDAC

Understanding the Problem: We have one input, an array. Our goal is to remove all the falsy values from the array then return the array.


The good people at freeCodeCamp have told us that falsy values in JavaScript are falsenull0""undefined, and NaN.

They have also dropped a major hint for us! They suggest converting each value of the array into a boolean in order to accomplish this challenge. I think that’s a great hint!

Examples/Test Cases: Our provided test cases show us that if the input array only contains falsy values, then we should just return an empty array. That’s pretty straightforward.

Data Structure: We are going to stick with arrays here.

Let’s talk about .filter():

.filter() creates a new array with all elements that pass the test implemented by the provided function.

In other words, .filter() goes through each element in an array and preserves all the elements that pass a certain test. All the elements in the array that fail that test are filtered out — they’re removed.

For example, if we had an array of numbers and we only wanted the numbers greater than 100, we could use .filter() to accomplish that:

let numbers = [4, 56, 78, 99, 101, 150, 299, 300]
numbers.filter(number => number > 100)
// returns [ 101, 150, 299, 300 ]

Let’s talk about the hint of converting each element to a boolean. This is a good hint because we can use .filter() to return the array with only the truthy values.

We’re going to accomplish that through JavaScript type conversion.

JavaScript gives us useful functions to convert one data type to another. String() converts to a string, Number() converts to a number, and Boolean() converts to a boolean.

For example:

String(1234)
// returns "1234"
Number("47")
// returns 47
Boolean("meow")
// returns true

Boolean() is the function we’ll be implementing with this challenge. If the argument provided to Boolean() is truthy, then Boolean() will return true.If the argument provided to Boolean() is falsy, then Boolean() will return false.

This is useful to us because we know from the instructions that only falsenull0""undefined, and NaN are falsy in JavaScript. Every other value is truthy. Knowing that, if we convert each value in the input array to a boolean, we can remove all elements that evaluate to false, and that will satisfy the requirements for this challenge.

Algorithm:

  1. Determine which values in arr are falsy.
  2. Remove all falsy values.
  3. Return the new array that contains only truthy values.

Code: See below!

function bouncer(arr) {
      // Use filter to remove falsy elements from arr.
      let onlyTruthyValues = arr.filter(element => Boolean(element) === true)
      //                                7          Boolean(7) is true
      //                                "ate"      Boolean("ate") is true
      //                                ""         Boolean("") is false
      //                                false      Boolean(false) is false
      //                                9          Boolean(9) is true

  // Return the new array.
  return onlyTruthyValues
  //     [7, "ate", 9]
}


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


Without comments and removing the local variable:

function bouncer(arr) {
      return arr.filter(element => Boolean(element) === true)
    }

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

If you have other solutions and/or suggestions, please share in the comments!

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Talking to Python from JavaScript (and Back Again!)

☞ Top 12 Javascript Tricks for Beginners

☞ Functional Programming in JavaScript

☞ JavaScript for Machine Learning using TensorFlow.js

☞ Learn JavaScript - JavaScript Course for Beginners

☞ The Complete JavaScript Course 2019: Build Real Projects!

☞ Become a JavaScript developer - Learn (React, Node,Angular)

☞ JavaScript: Understanding the Weird Parts

☞ Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

☞ The Full JavaScript & ES6 Tutorial - (including ES7 & React)

☞ JavaScript - Step By Step Guide For Beginners

☞ The Web Developer Bootcamp

☞ MERN Stack Front To Back: Full Stack React, Redux & Node.js







Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

How to Retrieve full Profile of LinkedIn User using Javascript

I am trying to retrieve the full profile (especially job history and educational qualifications) of a linkedin user via the Javascript (Fetch LinkedIn Data Using JavaScript)

Java vs. JavaScript: Know The Difference

Java vs. JavaScript: Know the Difference, Java vs. JavaScript: What's the Difference? Java vs. JavaScript: Major Similarities and Differences. pros and cons of JavaScript and Java.