JavaScript Tip: Remove ?falsy? Items Out of an Array
The new ECMAScript 5 brought a lot of enhancements that we used to see only on JavaScript frameworks. The Array
class now has methods like forEach
, map
& filter
, which are very useful.
If you need to support older browsers, which you probably do, this filtering method can be also found in MooTools (Array#filter
), jQuery ($.grep
) and other JS frameworks.
A quick tip to remove all falsy (false
, null
, undefined
, 0
, NaN
or an empty string) items out of an array:
1 2 |
|
Since Boolean
constructor is also a function, it returns either true
for ‘truthy’ argument or false
for ‘falsy’ argument.
For example:
1 2 3 4 5 |
|
And writing
1
|
|
is actually the same as writing:
1
|
|