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
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

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.