How to Remove All Falsy Values From JavaScript Array Easily

Robin
Updated on May 29, 2023

If a JavaScript array contains falsy values such as false, 0, null, undefined, NaN, and an empty string (''), it can give you unexpected results. These values also reduce the accuracy of your data.

That's why we need to remove all the falsy values from an array using various JavaScript methods and techniques. You can use built-in array methods for this.

We will explore different approaches to remove all falsy values from a JavaScript array. You can choose any one of those techniques.

Removing All Falsy Values From Array Using Boolean Constructor

To remove falsy values from a JavaScript array, you can utilize the filter() method in combination with the Boolean constructor. By providing the Boolean constructor as the filter function, this method effectively filters out all falsy values from the array, keeping only the truthy values.

This is the most easiest and concise way to remove all the falsy items from your array.

          const values = [0, 1, false, true, '', 'hello', null, undefined, 'world', NaN]

const filteredValues = values.filter(Boolean)

console.log(filteredValues)
// [ 1, true, 'hello', 'world' ]
        

Suppose, You have an array called values that contains different values, including falsy values like 0, false, an empty string '', null, undefined, and NaN.

To remove all these falsy values, you can call the filter() method on the array with the Boolean constructor. Here this constructor will work as the callback function.

The Boolean constructor in JavaScript evaluates each element in the array. If an element is truthy, it will be included in the resulting filtered array. If it is falsy, it will be filtered out.

Also Read: 4 Different Ways to Effectively Empty an Array in JavaScript


Removing All Falsy Values Using filter Method

You can also use the filter() method without the Boolean constructor. Instead of passing this constructor, you can pass an anonymous function to filter out all the falsy values for your array.

          const values = [0, 1, false, true, '', 'hello', null, undefined, 'world', NaN]

const filteredValues = values.filter((value) => value)

console.log(filteredValues)
// [ 1, true, 'hello', 'world' ]
        

Here, you can call the filter() method with an arrow function as a callback. Inside the arrow function, value represents each element in the array.

It will evaluate the truthiness of each item from the array. If a value is truthy, it will be included in the resulting filtered array. If it is falsy, it will be filtered out.

          const values = [0, 1, false, true, '', 'hello', null, undefined, 'world', NaN]

const filteredValues = values.filter((value) => {
    if (value) {
        return value
    }
})

console.log(filteredValues)
// [ 1, true, 'hello', 'world' ]
        

You can also manually check the values using the if statement. If the value is truthy, you will return the value from the callback function. In this way, the filtered array will only contain the truthy values.

Also Read: Best Ways to Check If a Variable is an Array in JavaScript


Removing All Falsy Values Using JavaScript Loops

JavaScript has different types of for loops to iterate over an array. You can make use of these loops to filter out falsy values from your array.

We will discuss the following loops with examples:

  • Using for...of loop.
  • Standard for loop.
  • Using forEach loop.

Using for...of Loop

To remove falsy values using the for...of loop, you need to initialize an empty array. When you iterate over your array with the for...of loop, it will give you each item.

          const values = [0, 1, false, true, '', 'hello', null, undefined, 'world', NaN]

const filteredValues = []

for (const value of values) {
    if (value) {
        filteredValues.push(value)
    }
}

console.log(filteredValues)
// [ 1, true, 'hello', 'world' ]
        

For each value, you check if it is truthy by using it as a condition in an if statement. If the value is truthy, you push it into the filteredValues array using the push() method.

After completing the loop, the filteredValues array will only contain the truthy values.

Also Read: Conditionally Define or Add Elements to a JavaScript Array


Standard for Loop

When you iterate over an array using for loop, you can access each item with its index value. Get the value from your array using the index and check whether it is true.

          const values = [0, 1, false, true, '', 'hello', null, undefined, 'world', NaN]

const filteredValues = []

for (let i = 0; i < values.length; i++) {
    if (values[i]) {
        filteredValues.push(values[i])
    }
}

console.log(filteredValues)
// [ 1, true, 'hello', 'world' ]
        

If the element is truthy, you can push it into the filteredValues array using the push() method.

Also Read: Remove Duplicates From a JavaScript Array Like a Pro (Easy)


Using forEach Loop

You can call the forEach() method on your array to loop through each item. The callback function of this method will run for every element of the array.

          const values = [0, 1, false, true, '', 'hello', null, undefined, 'world', NaN]

const filteredValues = []

values.forEach((value) => {
    if (value) {
        filteredValues.push(value)
    }
})

console.log(filteredValues)
// [ 1, true, 'hello', 'world' ]
        

Using the forEach() method, you iterate over each element value in the values array. For each element, you check if it is truthy by using it as a condition in an if statement.

If the element is truthy, meaning it is not falsy, you push it into the filteredValues array using the push() method.

After iterating over all the elements in the values array, you have a new array called filteredValues that only contains the truthy values from the original values array.

Also Read: Store and Get JavaScript Arrays in localStorage [Many Ways]


Removing All Falsy Values With reduce Method

In JavaScript, the reduce() method provides a powerful way to iterate over an array and accumulate values. By leveraging this method, you can easily remove falsy values and build a new array containing only truthy values.

          const values = [0, 1, false, true, '', 'hello', null, undefined, 'world', NaN]

const filteredValues = values.reduce((accumulator, current) => {
    if (current) {
        accumulator.push(current)
    }
    return accumulator
}, [])

console.log(filteredValues)
// [ 1, true, 'hello', 'world' ]
        

In this example, Our goal is to remove these falsy values and create a new array called filteredValues containing only the truthy values.

The reduce() method takes two main arguments: a callback function and an initial value for the accumulator. The callback function accepts two parameters: the accumulator and the current value being processed.

By providing an initial value of an empty array [] as the second argument to reduce(), we ensure that the accumulator starts as an empty array.

Within the callback function, you check if the current value is truthy by using it as a condition in an if statement. If the value is truthy, indicating it is not falsy, you will push it into the accumulator array using the push() method.

Finally, you need to return the accumulator at the end of each iteration. This collects all the truthy values as you iterate through the array.

When the loop completes, the filteredValues array will only contain the truthy values for the original values array.

Also Read: In-Depth Guide to Shuffle Any Type of JavaScript Array


Conclusion

To ensure accurate data processing and filtering, it is essential to have truthy values in your JavaScript array. I have shown you a number of ways to filter out your array.

We learned how to use the Boolean constructor, the filter() method, JavaScript loops (including the standard for loop, for...of loop, and forEach() method), and the reduce() method to remove falsy values from an array.

The Boolean constructor and the filter() method provide concise and elegant solutions. JavaScript loops offer flexibility and control, you can add custom conditional logic. The reduce() method allows for the accumulation and transformation of array values.

Choose the method that best suits your requirements and coding style. By applying these techniques, you can easily remove falsy values from JavaScript arrays and ensure the accuracy of your data.

Related Posts