Basic Algorithm Scripting : Falsy Bouncer
I was using JavaScript’s .filter() method to solve this problem, when I unexpectedly stumbled upon a solution. Can anybody explain to me why arr.filter(ele => ele) removed all of the falsy values from the array? I was planning on adding some logic to filter further in order to solve the problem but noticed that this simple piece of code worked. Problem and solution below:
Problem:
Remove all falsy values from an array:
bouncer([7, “ate”, “”, false, 9]);
Falsy values in JavaScript are false
, null
, 0
, ""
, undefined
, and NaN
.
Solution:
function bouncer(arr) {
// Don't show a false ID to this bouncer.
let newArr = arr.filter(ele => ele);
console.log(newArr);
return newArr;
}
bouncer([7, "ate", "", false, 9]);