Akshay
Akshay

Reputation: 45

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.

Upvotes: 2

Views: 1373

Answers (2)

Diego Polido Santana
Diego Polido Santana

Reputation: 1435

Check this out:

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

Plunker: https://plnkr.co/edit/csauovjhFeFltkbqRxjx?p=preview

Upvotes: 0

PhilVarg
PhilVarg

Reputation: 4811

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"]);

Upvotes: 1

Related Questions