javascript

Javascript code to remove falsy value like null, undefined, false from array

The code can be used to remove falsy values from an array using Javascript. Values like null, undefined, blank string, false are considered as falsy values.

const my_array = [10, false, null, "devsheet", undefined];
const filtered_array = my_array.filter(Boolean);
// -> [10,"devsheet"]

We are using Array.filter(Boolean) to filter out falsy values from the array. We have created an array my_array that contains the blank strings, false, null, and undefined items in it. It will filter all these values and return a new array in the filtered_array variable.

Live Demo

const fruits = ["apple", false, "banana", null, undefined];
const filtered_fruits = fruits.filter(function (value) {
    return value ? true : false;
});
console.log(filtered_fruits);
We are given an array named fruits and we want to filter the falsy values from it. We are using Array.filter() method here and getting filtred array in filtered_fruits constant.
Was this helpful?