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!

Bonfire: Slasher Flick

Use either .splice() or .slice() to get the answer to this coding challenge from FreeCodeCamp.

The Challenge:

Return the remaining elements of an array after chopping off n elements from the head.

The head meaning the beginning of the array, or the zeroth index


My Solution:

function slasher(arr, howMany) {
  // it doesn't always pay to be first
  arr = arr.slice(howMany, arr.length);
  return arr;
}

slasher([1, 2, 3], 2);

I used the .slice() method and sliced starting at the howMany value, through the length of the array. This challenge took me about ten minutes! Are they getting easier or am I just getting better? I hope it’s the latter!

Bonfire: Factorialize a Number

Factorialize a Number – great JavaScript coding challenge from free online full-stack bootcamp FreeCodeCamp. This was a tough one that required a couple hours to figure out. Taking a break from these challenges really makes them harder when you start back up!

Challenge:

Return the factorial of the provided integer.

If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n.

Factorials are often represented with the shorthand notation n!

For example: 5! = 1 * 2 * 3 * 4 * 5 = 120


Solution:

function factorialize(num) {
  var total = 1;
  for (var i = 0; num > i; i++) {
    total = total * (i+1);
  }
  return total;
}

factorialize(5);

Bonfire: Chunky Monkey

The Chunky Monkey Bonfire took me about 40 minutes to solve. It was a real tough one and I had to Google to find some help.  I used the .push() method and the .slice() method. Came across Wulkan’s blog in my search and his solution to the challenge really helped me find mine. Thanks Wulkan!

The Challenge:

Bonfire: Chunky Monkey

Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a multidimensional array.

For example:
chunk(["a", "b", "c", "d"], 2) should return [["a", "b"], ["c", "d"]]
chunk([0, 1, 2, 3, 4, 5], 3)
 should return [[0, 1, 2], [3, 4, 5]]


The Solution:

function chunk(arr, size) {

  var newArr = [];
  for (i = 0; i < arr.length;) {
    newArr.push(arr.slice(i, i += size));
  }
  return newArr;
 
}

chunk(["a", "b", "c", "d"], 2, "");

I was having trouble with controlling the incrementation in the ‘for loop’ so I just took out the ‘i++’ and it worked!

Bonfire: Truncate a string

Using .splice() to solve FreeCodeCamp‘s Bonfire: Truncate a string.

The Challenge:

Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a “…” ending.

Note that the three dots at the end add to the string length.

Try it yourself before viewing my solution! If you use Google Chrome as your browser, you can right click and Inspect Element to use the console to test your code.


The Solution:

function truncate(str, num) {

  if (str.length > num) {
    return str.slice(0, (num-3)) + "...";
  } else {
    return str;
  }
}

truncate("A-tisket a-tasket A green and yellow basket", 11, "");
truncate("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length);

Bonfire: Repeat a String Repeat a String

Three in a row! Are these challenges easier than the first Bonfires or is all this training really starting to improve my programming brain? (I hope it’s the latter!)

This is my solution to FreeCodeCamp‘s Bonfire: Repeat a string repeat a string. This one was much easier to complete as you only need to check if the num argument is less than zero.

The Challenge:

Repeat a given string (first argument) n times (second argument). Return an empty string if n is a negative number.

The Solution:

function repeat(str, num) {

  if (num < 0) {
    return "";
  } else {
    return str.repeat(num);
  }
}

repeat("*", 3, "");
repeat("abc", 3, "");

Bonfire: Return Largest Numbers in Arrays

Took me about an hour, but I finally passed the Bonfire: Return Largest Numbers in Arrays from FreeCodeCamp’s Algorithm section. Whoohoo!

The Challenge:

Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.

The Solution:

function largestOfFour(arr) {

  var newArray = [];
  var x = 0;
  for (var i = 0; i < arr.length; i++) {
    for (var j = 0; j < arr[i].length; j++) {
      if (x < arr[i][j]) {
        x = arr[i][j];       
      }
    }
   newArray.push(x);
    x = 0;
  }
  return newArray;
}


largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

There is a much easier way, by using the math.max.apply method, but I didn’t choose to use it.