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
var a=[1,2,"b",0,{},"",NaN,3,undefined,null,5];
var b=a.filter(Boolean); // [1,2,"b",{},3,5]

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
Boolean(0); // false
Boolean(true); // true
Boolean(1); // true
Boolean(""); // false
Boolean("false"); // true. "false" is a regular, non-empty string

And writing

1
b=a.filter(Boolean);

is actually the same as writing:

1
b=a.filter(function (x) { return Boolean(x); });

Comments