ArticleZip > Remove All Falsy Values From An Array

Remove All Falsy Values From An Array

One common task when working with arrays in programming is to remove falsy values. Falsy values are values that are considered false when converted to a Boolean. This includes values like `false`, `0`, `NaN`, `null`, `undefined`, and an empty string (`""`).

Removing these falsy values from an array can be essential when you want to clean up your data or filter out unwanted elements. In this article, we will walk you through a simple and efficient way to remove all falsy values from an array using JavaScript.

To begin, let's create a sample array that contains both truthy and falsy values:

Javascript

const mixedArray = [0, 1, false, 2, "", 3, NaN, "Hello", null, undefined, 4];

Now, here is a common approach to filter out all falsy values from the `mixedArray` using the `filter()` method in JavaScript:

Javascript

const filteredArray = mixedArray.filter(Boolean);

In the code snippet above, `Boolean` is a built-in JavaScript function. When you pass it as the argument to the `filter()` method, it acts as a callback function that will be executed for each element in the array. The `filter()` method will keep only the elements for which the callback function returns `true`, effectively removing all falsy values from the array.

Let's test the `filteredArray` and see the results:

Javascript

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

As you can see, the new `filteredArray` now contains only truthy values from the original `mixedArray`, and all falsy values have been removed successfully.

If you prefer a more explicit approach, you can achieve the same result by creating a custom filtering function like this:

Javascript

function removeFalsyValues(arr) {
  return arr.filter(element => {
    return Boolean(element);
  });
}

Now you can use the `removeFalsyValues` function to clean up any array from falsy values:

Javascript

const anotherArray = [false, 0, "Hello", NaN, 42];
const cleanedArray = removeFalsyValues(anotherArray);

console.log(cleanedArray); // Output: ["Hello", 42]

And that's it! You now know how to quickly and efficiently remove all falsy values from an array in JavaScript. This technique can be very useful when working with data manipulation or filtering tasks in your projects.

×