DEV Community

Discussion on: 1 line of code: How to clean an Array

Collapse
 
lexlohr profile image
Alex Lohr • Edited

Interesting is that all these filtered can be coerced to false, and only the number 0 and false can, too. That would simplify the filter to:

arr.filter(item => !!item || item === 0 || item === false);
Enter fullscreen mode Exit fullscreen mode

EDIT: The original article did something like:

arr.filter(item => typeof item === 'number' && !isNaN(item) || typeof item === 'boolean' || !!item);
Enter fullscreen mode Exit fullscreen mode

Now that it is updated, the above doesn't seem to make sense, obviously.

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Why not just this?

arr.filter(i=>i)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lexlohr profile image
Alex Lohr

Because it was explicitly stated that false and 0 should not be filtered. Your code would filter them.

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Ah, I misread - you want to keep 0 and false. In which case, you can shorten to:

arr.filter(item => item || item === 0 || item === false)
Enter fullscreen mode Exit fullscreen mode

The !! is unnecessary.

Collapse
 
martinkr profile image
Martin Krause

Hi,

thank you for the simplification! I updated the article and the code.

Cheers!

Collapse
 
jamesthomson profile image
James Thomson

Next time I suggest posting an edit rather than overwriting the old article. The comment above makes no sense given the new article context.