I would like to remove all falsy values from an array. Falsy values in JavaScript are false, null, 0, \"\", undefined, and NaN.
This is my idea...
function bouncer(arr) {
// Don't show a false ID to this bouncer.
var result = [];
function isGood(obj){
if(!Boolean(obj)){
return false;
} else {
return true;
}
}
for (var i=0; i < arr.length; i++){
if (isGood(arr[i]) === true){
result.push(arr[i]);
}
}
return result;
}
console.log(bouncer([7, "ate", "", false, 9]));
function bouncer(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i]) {
result.push(arr[i]);
}
}
return result;
}
bouncer([7, "ate", "", false, 9]);
Using this simple filter will do:
array.filter(Boolean)
You can read more about Boolean
here
This should be what you are looking for:
let array = [7, 'ate', '', false, 9, NaN];
function removeFalsyItems(array) {
// Your result
let filter = array.filter(Boolean);
// Empty the array
array.splice(0, array.length);
// Push all items from the result to our array
Array.prototype.push.apply(array, filter);
return array
}
removeFalsyItems(array) // => [7, 'ate', 9], funny joke btw...
Try using filter and Boolean:
let array = [7,"ate","",false,9];
array.filter((values) => {return Boolean(values) === true })
function bouncer(arr) {
function filterFalse(value) {
var a = Boolean(value);
if (a === true) {
return a;
}
return a;
}
function filterArray(x) {
var y = filterFalse(x);
if (y) {
return true;
} else {
return false;
}
}
var newArr = arr.filter(filterArray);
return newArr;
}
bouncer([1, null, NaN, 2, undefined]);