Bonfire: Falsy Bouncer

Challenge:

Remove all falsy values from an array.

Falsy values in JavaScript are false, null, 0, “”, undefined, and NaN.

Use the following:
Array.filter()
Boolean objects


My Solution:

function bouncer(arr) {
  // Don't show a false ID to this bouncer.

  var newArray = [];
  for (var i = 0; i < arr.length; i++) {
    var arrBool = Boolean(arr[i]);
    if (arrBool === true) {
      newArray.push(arr[i]);
      //return newArray;
    }
  }
  return newArray;
}


bouncer([7, "ate", "", false, 9]);

To approach this challenge, I broke it down like this (my thinking process):
1. I need to pass each element of the given array (arr) through a loop to check if each item value is 'false' or 'true'.
2. I can use the Boolean object to check if an item is false or true. I’ll do that within my loop.
3. I don’t know how to use Array.filter(), even after reading the Mozilla page. I’ll ignore that for now.
4. What kind of loop will allow me to iterate through each item in the array? I can use a ‘for loop‘.
5. Do I need to use split()? No, .split() only works for strings.
6. Oh, if you have an array, you can check each individually by using their index number, which starts with 0. So, [0=>7, 1=>”ate”, 2=>””, 3=>false, 4=>9]. Then I’ll start my ‘for loop’ variable ‘i’ at 0 (var i = 0), iterate the length of the array (i< arr.length), and increment by 1 because I want to go through every index in the array (i++).
7. I’ll use an if statement within my loop to check if the values are true or false.
8. After I check if the value is true or false, I want to take all the true values and put them somewhere. Maybe I’ll create a new array called newArray and store all the true values (var newArray = []). I want to be able to return the newArray so I’ll declare this newArray outside of my loop.
8. To add items to an array, you can use .push(), with what you want to push included inside the parentheses.
9. I tried to do newArray = newArray.push(arr[i]); but was getting an error. I removed newArray = and now it works! Will need to look into why that is later.
10. I want to return the new array, so I’ll write return newArray outside of my for loop.
11. I also want to return my newArray in my if statement so that the for loop can access the newArray values.
12. Well, returning the newArray within my if statement causes an error, so I’ll comment that out.
13. Yay! Passed all tests!

Advertisements