Skip to content

How to remove empty and falsy values from an array Using Javascript

You can remove empty and falsy values from an array using the filter method. Below are the examples:

Using Boolean as a function

const items = [1, null, false, "",'','test','1', 0];
const filteredItems = items.filter(Boolean); 
// This will filter out falsy values. 
console.log(`Filtered items`,filteredItems); 
//Output: Filtered items  [1, 'test', '1']

Using Filter

const items = [1, null, false, "",'','test','1', 0];
const filteredItems = items.filter(el => el); 
// This will filter out falsy values. 
console.log(`Filtered items`,filteredItems); 
//Output: Filtered items  [1, 'test', '1']

In the above two examples filter() method removed all the falsy values from the array. However, If you want to remove only specific elements from the array you should customize the filter callback as shown below.

const items = [1, null, false, "",'','test','1', 0];

// Define a custom filter function
function myFilter(elm){
    return (elm != null && elm !== false && elm !== "");
}
const filteredItems = items.filter(myFilter); 
// This will filter out falsy values. 
console.log(`Filtered items`,filteredItems); 
//Output: Filtered items  [1, 'test', '1', 0]
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments