JavaScript check if letter is contain or not in a string

Viewed 133

I have the following JavaScript function using which I want to check if the first element of the array called mutation contains all the letters of the second element.

function mutation(arr) {
  let test    = arr[1].toLowerCase();
  let target  = arr[0].toLowerCase();

  let split = test.split('');

  split.forEach((elem)=>{
    if(target.indexOf(elem) < 0 ) {
      return false;
    }
  });
  return true;
}

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

Now it should show me boolean false because letter y does not exist in hello word. but it's doesn't.

Is there anything I am doing wrong?

5 Answers

You may use Array.prototype.every()

function mutation(arr) {
  let test = arr[1].toLowerCase();
  let target = arr[0].toLowerCase();
  let split = test.split('');
  return split.every(x => target.includes(x)); // checks if all letters of `split` exists in `target`
}
console.log(mutation(["hello", "hey"]));
console.log(mutation(["hello", "heo"]));
console.log(mutation(["helloworld", "lloword"]));

You can try another approach to get the expected results:

function mutation(arr) {
  let test    = arr[1].toLowerCase().split('').join('');
  let target  = arr[0].toLowerCase().split('').join('');
  return target.includes(test);
}

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

I would do:

function mutation(arr) {
  let test    = arr[1].toLowerCase();
  let target  = arr[0].toLowerCase();
  return target.includes(test);
}

console.log(mutation(["hello", "hey"]));
console.log(mutation(["helloworld", "hello"]));

The Return statement inside the ForEach won't return from the function, you can use a simple for loop or a reduce to get the end result in on line

function mutation(arr) {
  let test    = arr[1].toLowerCase();
  let target  = arr[0].toLowerCase();

  let split = test.split('');

  const result = split.reduce((acc, curr) => acc && target.includes(curr), true);

  return result;
}

console.log(mutation(['hello', 'y']));

Stick to more classical methods:

console.log(mutation(["hello", "hey"]));

function mutation(args) {
  const target  = args[0].toLowerCase();
  const test    = args[1].toLowerCase();
  
  for(let i = 0; i < test.length; i += 1) {
  
    if (target.indexOf(test[i]) < 0) {
      return false;
    }
    
  }
  return true;
}

Related