A falsy bouncer algorithm is a step by step approach to removing all false or falsy values usually from an array. Falsy values includes: false
, null
, undefined
, 0
, NaN
, and ""
.
falsyBouncer([undefined, 1, 0, 60000, null, NaN, '', "njoku Samson"])
// [ 1, 60000, 'njoku Samson' ]
Do you think this is achievable? How can this be done?
Let me share 4 ways to bounce falsy values from an array.
Prerequisite
This article assumes that you have basic understanding of javascript's array methods.
Let's bounce falsy values from an array using:
- for...of...loop, push()
function falsyBouncer(array) {
let sanitizedArray = [];
for (element of array) {
element ? sanitizedArray.push(element) : sanitizedArray;
}
return sanitizedArray;
}
- forEach...loop, includes(), push()
function falsyBouncer(array) {
let falsyValues = [false, null, undefined, 0, NaN, ""];
let sanitizedArray = [];
array.forEach(element => {
!falsyValues.includes(element)
? sanitizedArray.push(element)
: sanitizedArray;
});
return sanitizedArray;
}
- filter()
function falsyBouncer(array) {
let sanitizedArray = array.filter(element => Boolean(element));
return sanitizedArray;
}
- reduce()
function falsyBouncer(array) {
let sanitizedArray = [];
sanitizedArray = array.reduce((acc, element) => {
if (Boolean(element)) {
return [...acc, element];
} else {
return acc;
}
}, []);
return sanitizedArray;
}
Conclusion
There are many ways to solve problems programmatically. I will love to know other ways you solved yours in the comment section.
If you have questions, comments or suggestions, please drop them in the comment section.
You can also follow and message me on social media platforms.
Thank You For Your Time.
Top comments (2)
I think that the third way of implementing a falsy bouncer is the easiest and shortest way. It doesn't get simpler than applying
reduce
with an arrow function.Thank you Ali for taking your time to read through.
The idea was just to show different way to solving one problem but in no particular order.