W3jar
299 words
1 minutes

How to Remove All Falsy Values from an Array in JavaScript

In JavaScript, you can remove all falsy values from an array using a variety of methods. Here are a few common approaches:

1. Using the filter Method#

The filter method creates a new array with all elements that pass the test implemented by the provided function. To remove falsy values, you can use it with a callback function that checks for truthiness:

const array = [0, "hello", false, 42, "", null, undefined, true];
const truthyArray = array.filter(Boolean);

console.log(truthyArray); // Output: ['hello', 42, true]

Here, Boolean is a built-in constructor that converts values to their boolean equivalent, effectively filtering out all falsy values.

2. Using a for Loop#

If you prefer not to use filter, you can manually iterate through the array and build a new array with only the truthy values:

const array = [0, "hello", false, 42, "", null, undefined, true];
const truthyArray = [];

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

console.log(truthyArray); // Output: ['hello', 42, true]

3. Using reduce#

The reduce method can also be used to accumulate only truthy values into a new array:

const array = [0, "hello", false, 42, "", null, undefined, true];
const truthyArray = array.reduce((acc, value) => {
    if (value) {
        acc.push(value);
    }
    return acc;
}, []);

console.log(truthyArray); // Output: ['hello', 42, true]

4. Using forEach#

Another approach is to use forEach to iterate over the array and collect truthy values:

const array = [0, "hello", false, 42, "", null, undefined, true];
const truthyArray = [];

array.forEach((value) => {
    if (value) {
        truthyArray.push(value);
    }
});

console.log(truthyArray); // Output: ['hello', 42, true]

Summary#

  • filter(Boolean) is the most concise and idiomatic way to remove falsy values from an array.
  • Manual loops (for, forEach) and reduce provide more control and might be preferred in more complex scenarios.

Choose the method that best fits your coding style and the needs of your project!