Javascript: Filter Falsy elements from an array

Javascript: Filter Falsy elements from an array

Table of contents

No heading

No headings in the article.

In this post am going to share a Javascript one liner to remove falsy elements from array, to put it more descriptive create a new array with truthy elements from an existing array.

Few days back, I came across an implementation requirement to display address details from an API in the below format

const address = {
  address1: 'Maple street',
  address2: null,
  city: 'Texas',
  postalcode: '1000',
  company: null
}

as user readable text on the web page as following

shipping address: 'Maple street, Texas, 1000'

So the requirement is that the object property that has value (that is truthy value) should be displayed on the web page. For this approach I thought to check on the each property of the address object whether it is available or not. In the above example, if address2 value is available then it should also get displayed on the web page.

Instead of checking on each property value, I came across a simple Javascript one liner to solve the problem.

This code snippet removes all falsy elements from the original Arr array and returns a new array containing only the truthy elements.

Code Snippet:

This approach removes elements like null, “” (empty string), 0 and false.

If you specifically want to keep falsy values like 0 or "", you'll need a custom function passed to filter that checks for specific conditions.

  • .filter(): This is a method available on arrays that creates a new array containing only elements that pass a test implemented by the provided function.

  • Boolean: Here, Boolean acts as a function. It's a shortcut for using the Boolean() constructor, which coerces any value passed to it into a boolean (true or false).