I have seen how to remove falsy values from an array but haven’t found a solution for returning a new array with all truthy elements removed. I attempted to replace falsy values with truthy ones in my "solution" but the results are not leaving me with an array with only falsy values.
var removeTruthy = function (arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == true || (arr[i]) == {} || arr[i] == "0" || arr[i] == 5 || arr[i] == Infinity || arr[i] == "hello") {
arr.splice(i, 1);
i--;
}
}
return arr;
}
2
Answers
All you need is
.filter()
To filter out all the falsy,
.filter(element => element)
.To filter out all the truthy, this: