DEV Community

Rajnish Katharotiya
Rajnish Katharotiya

Posted on

Remove all falsy values from array in javascript

Hi folks, Welcome back on another episode of this exciting series called: Javascript useful snippets. In this series of episodes, we are discussing some shortcodes or useful functions, which can help you to make your development more efficient and faster. So, stay tuned till the end…

Javascript Useful Snippets — compact()

Array with massive values, we would like to filter it more often or remove all falsy values ( like 0, NaN, undefined, ‘’, false ) at those times we can use this snippet. the compact() function will take any set of values in an array and return only-n-only truthy values of the array as a result. So, let’s see how it works…

const compact = arr => arr.filter(x => Boolean(x));
// const compact = arr => arr.filter(Boolean); or you could write like this

In the above syntax, a filter is being used to return an only true value. well, the filter basically works like, you need to pass prediction in callback’s return so if record match with your given prediction then it’ll store it in a new array ( in our case compact ) else record will be omitted.

Result :

const result = compact([ 0, 1, false, 2, ‘’, 3, ‘a’, NaN, ‘e’ ]); // output: [ 1, 2, 3, “a”, “e” ]

there you go, as you have seen in the result of output all falsy values ( like 0, false, “”, NaN ) neglect from an array and we got compacted array with our desired values, cheers!!

Now, what if we want to check whether all records of the array are equal or not? Well our next episode it all about it so, stay tuned and keep support me.

Thank you for watching folks, if you found this informative and wanted to make me more content like this please support me on Patreon.

Subscribe on youtube https://www.youtube.com/channel/UCvNjso_gPQIPacA6EraoZmg
Facebook: https://www.facebook.com/KatharotiyaRajnish/
Twitter: https://twitter.com/tutorial_spot

Top comments (1)

Collapse
 
syedsimanta03 profile image
syedsimanta03

what about ' ' space between it