I would like to remove all falsy values from an array. Falsy values in JavaScript are false, null, 0, \"\", undefined, and NaN.
I know this can be done using the arr.filter() method. But I prefer using the Boolean() function. Is clearer to me. Here's how I did it, although a little longer:
function bouncer(arr) {
// Don't show a false ID to this bouncer.
var falsy;
var trueArr = [];
for (i = 0; i < arr.length; i++) {
falsy = Boolean(arr[i]);
if (falsy === true) {
trueArr.push(arr[i]);
}
}
return trueArr;
}
bouncer([7, "ate", "", false, 9]);
// returns a new array that is filtered accordingly.