How to Filter for True Values in an Array in JavaScript

How to Filter for True Values in an Array in JavaScript

Ferenc Almasi β€’ Last updated 2021 April 26 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

Probably one of the simplest and cleanest ways to get rid of falsy values in JavaScript is by utilizing the built-in filter array function the following way:

Copied to clipboard! Playground
// Filter out falsy values by simply passing Boolean to Array.prototype.filter
[
  1, 2, 3, 0, 
  undefined, 
  null, 
  false, 
  true, 
  '', 
  'I’m truthy πŸ™‚'
].filter(Boolean);

// Results in the following array:
[1, 2, 3, true, 'I’m truthy πŸ™‚'];
filter.js

The only problem is that this won't work for nested arrays. To get around this, you can use the below function which uses recursion to filter out falsy values from a nested array:

Copied to clipboard! Playground
const filterFalsy = array => array.filter(Boolean)
                                  .map(item => Array.isArray(item) ? filterFalsy(item) : item);

const array = [
  1, 2, 3, 0, 
  undefined, 
  null, 
  false, 
  true,
  [0, 1, 2, '', [false, true]], 
  '', 
  'I’m truthy πŸ™‚'
];

filterFalsy(array); // This will return the following array:

[1, 2, 3, true, [1, 2, [true]], "I’m truthy πŸ™‚"]
filter.js
How to Filter Out Falsy Values From Array in JavaScript
If you would like to see more Webtips, follow @flowforfrank

Resource

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.