Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter empty space, null and undefined but keep `0`

I would like to keep 0 and need to remove undefined, null '' ,, from the array. I tried this:

var array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,];

var filtered = array.filter(function (el) {
  return el !== null
});

console.log(filtered);

But getting result as : [0, 1, 2, '', 3, undefined, 3, 4, 4, 5, 6]

if I add the condition as return el != null, still empty space exist and getting error from lint. how to handle this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

thanks in advance

>Solution :

You can use return e || e === 0 to filter it

var array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,];

var filtered = array.filter(e =>{ 
  return e || e === 0
})

console.log(filtered);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading