How to Filter for True Values in an Array in JavaScript

How to Filter for True Values in an Array in JavaScript

Ferenc Almasi β€’ πŸ”„ 2021 April 26 β€’ πŸ“– 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:

// 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
Copied to clipboard!

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:

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
Copied to clipboard!
How to Filter Out Falsy Values From Array in JavaScript
If you would like to see more Webtips, follow @flowforfrank
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

Resource

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro

Recommended

Ezoicreport this ad