user3838937
user3838937

Reputation: 51

Why is my while loop not iterating through completely?

So this is my code below, the goal is for this program is to check to see if the letters of the second string can be found in the first string. However I found the problem that i isn't, increasing in value. So the loop is only going through once. So this program ends at the first letter that it finds and returns true. How do I get i to increase so that it's iterating through every character of the string?

function mutation(arr) {
  var str = arr[1];
  str = str.toLowerCase().split("");
  var i = 0;
  while (i < arr.length) {
    if (arr[0].indexOf(str[i]) > -1) {
      //return  arr[i].indexOf(str[i], i);
      return true;
    } else {
      return false;
    }
    i++;
  }
}

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

Upvotes: 1

Views: 65

Answers (3)

James
James

Reputation: 22237

Totally different technique.

This function replaces, in the second string, all letters from the first string with empty space. If the length is zero all letters were found.

function mutation(arr) {
  return arr[1].replace(new RegExp("[" + arr[0] + "]", "g"), "").length == 0;
}

Upvotes: 0

Billy Moon
Billy Moon

Reputation: 58521

function mutation(arr) {
  var base = arr[0],
      str = arr[1].toLowerCase().split(''),
      i = 0,
      match = true;
  while (i < str.length) {
    // if any target letter is not in base, return false
    if(base.indexOf(str[i]) === -1){
        return false;
    }
  }
  // otherwise they were all in, so return true
  return true;
}
mutation(["hello", "hey"]);

Upvotes: 0

James
James

Reputation: 22237

This maybe?

function mutation(arr) {
  var str = arr[1];
  str = str.toLowerCase().split("");
  // iterating an array screams "for loop"
  for (var i=0; i < str.length; i++) {
    // if the letter was not found exit immediately
    if (arr[0].indexOf(str[i]) == -1) return false;
  }
  // since it didn't exit before, all the letters must have been found.
  return true;
}

Upvotes: 2

Related Questions