Remove all falsy values from an array.
Hint: Try converting each value to a Boolean.
Provided Test Cases
bouncer([7, "ate", "", false, 9])should return
[7, "ate", 9].
bouncer(["a", "b", "c"])should return
["a", "b", "c"].
bouncer([false, null, 0, NaN, undefined, ""])should return
bouncer([1, null, NaN, 2, undefined])should return
Solution #1: .filter( ) and Boolean( )
Understanding the Problem: We have one input, an array. Our goal is to remove all the falsy values from the array then return the array.
They have also dropped a major hint for us! They suggest converting each value of the array into a boolean in order to accomplish this challenge. I think that’s a great hint!
Examples/Test Cases: Our provided test cases show us that if the input array only contains falsy values, then we should just return an empty array. That’s pretty straightforward.
Data Structure: We are going to stick with arrays here.
Let’s talk about
.filter() creates a new array with all elements that pass the test implemented by the provided function.
In other words,
.filter() goes through each element in an array and preserves all the elements that pass a certain test. All the elements in the array that fail that test are filtered out — they’re removed.
For example, if we had an array of numbers and we only wanted the numbers greater than 100, we could use
.filter() to accomplish that:
let numbers = [4, 56, 78, 99, 101, 150, 299, 300]numbers.filter(number => number > 100)// returns [ 101, 150, 299, 300 ]
Let’s talk about the hint of converting each element to a boolean. This is a good hint because we can use
.filter() to return the array with only the truthy values.
String() converts to a string,
Number() converts to a number, and
Boolean() converts to a boolean.
String(1234)// returns "1234"
Number("47")// returns 47
Boolean("meow")// returns true
Boolean() is the function we’ll be implementing with this challenge. If the argument provided to
Boolean() is truthy, then
Boolean() will return
true. If the argument provided to
Boolean() is falsy, then
Boolean() will return
This is useful to us because we know from the instructions that only
false, and that will satisfy the requirements for this challenge.
- Determine which values in
- Remove all falsy values.
- Return the new array that contains only truthy values.
Code: See below!
Without comments and removing the local variable:
If you have other solutions and/or suggestions, please share in the comments!