-
Notifications
You must be signed in to change notification settings - Fork 0
Algorithm Falsy Bouncer
Remove all falsy values from an array.
Falsy is something which evaluates to FALSE. There are only six falsy values in JavaScript: undefined, null, NaN, 0, "" (empty string), and false of course.
We need to make sure we have all the falsy values to compare, we can know it, maybe with a function with all the falsy values...
Then we need to add a filter() with the falsy values function...
Solution ahead!
function bouncer(arr) {
// Don't show a false ID to this bouncer.
// I've a hammer fist.
return arr.filter(Boolean);
}🚀 Run Code
function bouncer(arr) {
function isTruthy(arg) {
return Boolean(arg);
}
var filteredArray = arr.filter(isTruthy);
return filteredArray;
}🚀 Run Code
function bouncer(arr) {
arr = arr.filter(function(element){
return Boolean(element);
});
return arr;
}🚀 Run Code
The Array.prototype.filter method expects a function that returns a Boolean value which takes a single argument and returns true for truthy value or false for falsy value. Hence we pass the built-in Boolean function. The second solution replaces the array in-place, and utilises an anonymous function as the callback for the filter method. This avoids polluting the global scope with a single-use function, and makes our code more concise.
If you found this page useful, you can give thanks by copying and pasting this on the main chat: Thanks @renelis @abhisekp @Rafase282 for your help with Algorithm: Falsy Bouncer
NOTE: Please add your username only if you have added any relevant main contents to the wiki page. (Please don't remove any existing usernames.)
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links
