2

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.

devlin carnate
  • 8,309
  • 7
  • 48
  • 82
Akshay
  • 45
  • 7
  • 1
    check this [answer](http://stackoverflow.com/questions/37049306/how-to-check-two-string-have-same-characters-including-special-characters/37049804#37049804) – maioman May 10 '16 at 21:52
  • Possible duplicate of [How can I check if one string contains another substring?](http://stackoverflow.com/questions/1789945/how-can-i-check-if-one-string-contains-another-substring) – Heretic Monkey May 10 '16 at 21:55
  • I'd say exact duplicate of the answer @maioman pointed out; the one Mike pointed out answers finding a single substring within another string, but not matching for every individual character in a string within another string. – Dawson Toth May 10 '16 at 21:57
  • Neither of those are a duplicate. maioman's requires that all the characters are the same, or if not, that the missing chars of the second string. Mike's is looking for a substring. Neither are the same as this question. –  May 10 '16 at 22:09

2 Answers2

1

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"]);
PhilVarg
  • 4,762
  • 2
  • 19
  • 37
0

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

Diego Polido Santana
  • 1,425
  • 11
  • 19