I would like to remove all falsy values from an array. Falsy values in JavaScript are false, null, 0, \"\", undefined, and NaN.
function bouncer(arr) {
// Don't show a false ID to this bouncer.
for (var i = 0; i < arr.length; i++) {
if (!arr[i]) {
arr.splice(i, 1);
i = i-1;
}
}
return arr;
}
bouncer([7, "ate", "", false, 9]);
Thanks for all working answers above. Here are 3 approaches to solve the problem. Third solution addressed problem by your approach @Vignesh.
1.
function bouncer(arr) {
return arr.filter( function( val ){
return val;
});
}
2.
function bouncer(arr) {
return arr.filter(Boolean);
}
3.
function bouncer(arr) {
return arr.filter(function(val){
return val !== false && val !== "" && !(Number.isNaN(val)) && val !==
undefined && val !== 0 && val !== null;
});
}
Using filter we can write
function bouncer(arr) {
return arr.filter(item => item);
}
bouncer([false, null, 0, NaN, undefined, ""]) // will return [].
function falsy(value) {
if (value) {
return value;
}
}
function bouncer(arr) {
var filter = arr.filter(falsy);
return filter;
}
bouncer([7, "ate", "", false, 9]);