Remove all falsy values from an array in JavaScript

Remove all falsy values from an array in JavaScript

In this article you will learn 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.

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 false, null, 0, <em>""</em>, 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 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" target="_blank">.filter()</a>:

.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 false, null, 0, <em>""</em>, 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!

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

How to Clone an Array in JavaScript?

In this JavaScript tutorial, you'll learn how to clone an array in JavaScript. Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array.

JavaScript Array.flatMap()

JavaScript Array.flatMap(): Use flatMap to map over an array and flatten the result array in one go! Now lets up the game and introduce "flatMap". It combines the steps of first mapping over the array with `map()` & then calling `flat()`. Instead of calling 2 methods, just use `flatMap()` 👍