Help with the Mutations algorithm

Hi.

I’m stuck at this challenge. My idea is to return false if there are no matches, or true if all letters are found, but for some reason I can’t return the value I need (false).

Do you know why this doesn’t work?

Here is my code:

Spoiler
function mutation(arr) {
  var firstWord = arr[0].split('');
  var secondWord = arr[1].split('');

  secondWord.forEach(function(character) {
    if (firstWord.indexOf(character) === -1) {
      return false;
    }
  });

  return true;
}

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

There is both String.indexOf() and Array.indexOf(), so splitting is Okay.

Just as you said, I’ve just found out that you can’t break out of forEach, say I wanted to break it on the first falsy value of indexOf.

You can do exactly this with .every(), which is quite odd !

It turns out I was trying to return the value from within a callback function, which is what caused the weird behavior.

Thank you, @P1xt and @Mizu, you were very helpful, specially for the .every() tip. That method is awesome.

2 Likes