Follow

Follow

# Mutations - JavaScript Solution & Walkthrough

## (15/16) Learn how to solve coding challenges using FreeCodeCamp's curriculum.

Benjamin Semah
Â·Apr 15, 2022Â·

• 15/16 Mutations
• Understanding the Challenge
• Pseudocode
• Solving the Challenge
• Final Solution
• Congratulations!

## 15/16 Mutations

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.

Lastly, ["Alien", "line"], should return true because all of the letters in line are present in Alien.

function mutation(arr) {

return arr;
}

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

Credit: FreeCodeCamp.org

## Understanding the Challenge

You are expected to complete the mutation function. This function accepts two strings as arguments. The challenge is to complete the function such that it checks if the first string contains all of the letters in the second string. See the examples provided above in the challenge description.

If it contains all the letters, the function should return true. If it does not, the function should return false.

Note: We're informed that the function should ignore case (that is whether a letter is lower case or upper case.

## Pseudocode

Given two strings
convert both strings to lower case
loop through the second word
for each letter of the second word
check if it is included in the first word
if you find a word not included in the first word
return false
otherwise, return true

## Solving the Challenge

To make things more simple, we will first convert both strings to lowercase. That way, it is easy to compare.

const firstWord = arr[0].toLowerCase()
const secondWord = arr[1].toLowerCase()

Next, we are going to loop through the second word. For every iteration of the loop, we want to check whether or not the current letter is inclcuded in firstWord.

If we come accross a letter that is not included in firstWord, we return false.

However, we return true after the loop. This will only be return when all the letters of secondWord are present in firstWord

for (let i = 0; i < secondWord.length; i++) {
if (!firstWord.includes(secondWord[i])) {
return false
}
}
return true

## Final Solution

function mutation(arr) {
const firstWord = arr[0].toLowerCase()
const secondWord = arr[1].toLowerCase()

for (let i = 0; i < secondWord.length; i++) {
if (!firstWord.includes(secondWord[i])) {
return false
}
}
return true
}

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

## Congratulations!

You just cracked the 15th challenge in this series.

Cheers and happy coding!

Â