# Basic Algorithm Scripting (Mutations)

Hi!

I wonder how to return true or false depending on a condition result (line 23):
It should be like “if none of the items are equal, return false, otherwise, return true”.

How can I write this kind of loop? Thanks!

If you use a loop, you can check something at each iteration, if that thing is false you can return false inside the loop and break from the function. If nothing is false then the loop ends and you can return true
It can also be used inverting the return statements depending on what you need to check.
This would be the structure: (blurred in case you want to figure it from the above explanation)

``````for (...) {
if (...) {
return false;
}
}
return true;
``````

Basically a one liner:

``````function mutation(arr) {

return arr.toLowerCase().split('').every((letter) => arr.toLowerCase().indexOf(letter) >= 0);

}
mutation(["hello", "hey"]);
``````
2 Likes

Thanks, kerafyrm02
I did not know about every method. https://developer.mozilla.org/pl/docs/Web/JavaScript/Referencje/Obiekty/Array/every

Using two loops (checking character by character) is bad approach in this case?

Thank you leahleen.
But how does it refer to secondArr and equalChars ?

Didn’t you want to do something like that with this part of your code?
If you let it like this it will stop at k=0 and l=0.

``````for (let k=0; k < equalChars.length; k++) {
for (let l=0; l < secondArr.length; l++) {
if(equalChars[k] !== secondArr[l]) {
console.log(equalChars[k]);
//return false;

} else {
//return true;
}}}
``````

Yes, thank you.
But I am not sure how to write a loop which compares equalChars to secondArr.
This should be helpful to compare.

It is so painful to write these basic algorithms Using two nested loops would achieve the same thing.

In fact, my example and the example of using two loops is actually too slow. It would be O(n^2).

This example is O(n). Which would be significantly faster.

``````function mutation(arr) {

var validLetters = {};

for (let i = 0; i < arr.length; i = i + 1){
let letter = arr[i].toLowerCase();
validLetters[letter] = true;
}

for (let i = 0; i < arr.length; i = i + 1){
let letter = arr[i].toLowerCase();
if (!validLetters[letter]){
return false;
}
}

return true;

}
``````
1 Like

I will check it tomorrow. Thank you very much!

Incredible! You set each letter to true, and then, if it does not appear in the second array, return false.
Well done!

Hi @kerafyrm02,

I do not understand at the end of the code, Why .indexOf(letter) >= 0); ?? Greater or equal to zero.

Thank you for the help!

@AndresHMosqueda

If `letter` is found, indexOf will give you an index number at where it’s found anywhere from 0 to more.

If it’s not found, then it will be less than 0. So basically it’s checking to see if letter is existent.

@shimphillip.
Thanks Phillip