2

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?

Amod Shinde
  • 144
  • 9
Shibbir
  • 1,963
  • 2
  • 25
  • 48

5 Answers5

3

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"]));
Umair Khan
  • 1,684
  • 18
  • 34
1

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"]);
Abhishek
  • 539
  • 5
  • 25
  • 3
    I don't think this would work. Try with `['hello world', 'hello']`. The sorted strings are `[" dehllloorw", "ehllo"]`, where `includes` returns `false` – Maxime Helen Aug 04 '20 at 05:45
1

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"]));
Maxime Helen
  • 1,382
  • 7
  • 16
0

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']));
Alok Takshak
  • 282
  • 1
  • 6
0

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;
}
KooiInc
  • 119,216
  • 31
  • 141
  • 177