Akshay Akshay - 6 months ago 8
Javascript Question

How do I check if all the characters of a string are present in another string?

It's about a basic algorithm challenge, in which the user has to 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, e.g.:


  1. ["hello", "Hello"]
    should return
    true
    .

  2. ["Alien", "line"]
    should return
    true
    .



So far, I've tried this:

function mutation(arr) {
var value1 = arr[0].toLowerCase();
var value2 = arr[1].toLowerCase();
for (var i = 0; i < value2.length; i++) {
if (value1.indexOf(value2.charAt(i)) !== -1)
return true;
else
return false;
}
}
}
mutation(["hello", "hey"]);


While passing the value
mutation(["hello", "hey"])
, it isn't returning
false
.

Answer

it looks like youre pretty close, except you seem to be returning true early. Instead, if the indexOf returns -1 break from the loop and return false, otherwise let the loop run to completion and return true afterward (since it didnt return early, we know all chars are present)

function mutation(arr) {
   var value1 = arr[0].toLowerCase();
   var value2 = arr[1].toLowerCase();

  for(var i=0;i<value2.length;i++){
    if(value1.indexOf(value2.charAt(i)) === -1) { return false; }
  }
  return true;
}

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