JavaScript – Filter out falsy values from an array

In this post we will explore how to filter out falsy values from an array in JavaScript. Falsy values in JavaScript include false0""nullundefined, and NaN.

We will see three ways by which we can do this, one is by using the filter method, second one is using reduce and third by the standard loop.

Using filter()

const array = [0, 1, false, 2, '', 3, null, 4, undefined, 5, NaN];
const filteredArray = array.filter(Boolean);
console.log(filteredArray); // Output: [1, 2, 3, 4, 5]

In the above example, we have created a new array with all elements that pass the test implemented by the provided function.

By passing Boolean as the callback function, it effectively filters out all falsy values, since Boolean(value) returns false for any falsy value and true for truthy values.

Using reduce()

const array = [0, 1, false, 2, '', 3, null, 4, undefined, 5, NaN];
const filteredArray = array.reduce((acc, curr) => {
  if (Boolean(curr)) {
    acc.push(curr);
  }
  return acc;
}, []);

console.log(filteredArray);  // Output: [1, 2, 3, 4, 5]

In this example, we used the reduce method & pass two arguments, acc and curr. If curr is truthy we push it to acc. Initially the acc will be [] so at the end acc will contain only the truthy values.

Using loop

const array = [0, 1, false, 2, '', 3, null, 4, undefined, 5, NaN];
const filteredArray = [];

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

console.log(filteredArray); // Output: [1, 2, 3, 4, 5]

In this example, we loop through the array & for each item we check if its truthy using if condition. If the item is truthy we push it to filteredArray. In this way at the end filteredArray will contain only truthy values.

Similar Reads