Bonfire: Mutations

This challenge took me so ridiculously long!

The Challenge:

Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.

For example, ["hello", "Hello"], should return true because all of the letters in the second string are present in the first, ignoring case.

The arguments ["hello", "hey"] should return false because the string “hello” does not contain a “y”.

Use .indexOf()


The Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
function mutation(arr) {
  var firstArr = arr[0].toLowerCase().split('');
  var secondArr = arr[1].toLowerCase().split('');

  for (var i = 0; i < secondArr.length; i++) {
    var positive = firstArr.indexOf(secondArr[i]);
    if (positive === -1) {
      return false;
    };
  };
 
return true;
  
}

mutation(["hello", "hey"]);

To find the solution to this challenge, I first needed to compare all the letters of the two arguments with each other. To separate the letters of each word, I used .split(”) (see lines 2 and 3).

Since the second argument is shorter than the first, I only wanted to loop through the length of the second argument, in this case “hey”.

Using .indexOf(), I checked each letter of “hey” (secondArr) to see if the letters are in “hello” (firstArr). If the letter from secondArr is NOT in firstArr, the value of -1 will be saved to the variable positive.

Advertisements