Languages

JavaScript - filter null values from array

0 points
Asked by:
Vanessa-Drake
718

I need to remove falseundefinednull, 0, "" and NaN values from an array.

Anyone can help me with this?

// ONLINE-RUNNER:browser;

const myArray = [1, '', null, NaN, 2, undefined, 3];

const notAllowed = [null, '', false, 0, undefined, NaN];
1 answer
0 points
Answered by:
Vanessa-Drake
718

Use Boolean constructor to filter array from falsy values.

Your code should look like this:

// ONLINE-RUNNER:browser;

const myArray = [1, '', null, NaN, 2, undefined, 3];

const result = myArray.filter(Boolean);

console.log(JSON.stringify(result)); // [1,2,3]

 

See also

  1. JavaScript - remove all falsy values from array

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join