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?

3
  • 2
    You cannot return from inside forEach. Please refer stackoverflow.com/questions/34653612/… Commented Aug 4, 2020 at 5:28
  • Oh. I see!!! Thanks for that info. Commented Aug 4, 2020 at 5:31
  • 1
    Should mutation(["hello", "helo"]) return true? Commented Aug 4, 2020 at 5:44

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

I don't think this would work. Try with ['hello world', 'hello']. The sorted strings are [" dehllloorw", "ehllo"], where includes returns false
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"]));

Comments

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; }

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.