Using javascript, I want to check if the string in the 1st array element contains all the letters of the 2nd array element. If so, return true. E.g. ["Mary", "Aarmy"] => true; ["hello", "hey"] => false.
I've tried the following code, which works for ["Mary", "Aarmy"] and ["voodoo", "no"], but doesn't work for ["hello", "hey"]. Appreciate any help, thanks!
function mutation(arr){
var str1 = arr.pop().toLowerCase();
var str2 = arr.pop().toLowerCase();
for(var i = 0; i < str2.length; i++){
if(str1.indexOf(str2[i]) !== -1){
return true;
}
else return false;
}
}
When you use pop() it'll return the last element in the array and not the first.
Also your if else is inside for and has a return statement. This does not let the for loop run completely and returns after the very first loop.
function mutation(arr){
var str2 = arr.pop().toLowerCase();
var str1 = arr.pop().toLowerCase();
console.log("str1: " + str1);
console.log("str2: " + str2);
for(var i = 0; i < str2.length; i++){
if(str1.indexOf(str2[i]) === -1){
return false;
}
}
return true;
}
arr = ["hello", "hey"];
console.log(mutation(arr));
arr = ["Mary", "Aarmy"];
console.log(mutation(arr));
Considering you can use Set, and lodash, here is another solution:
const _ = require("lodash");
function mutation(arr) {
var set1 = new Set(arr.pop().toLowerCase().split(''));
var set2 = new Set(arr.pop().toLowerCase().split(''));
return _.isEqual(set1, set2);
}
console.log(mutation(["Mary", "Aarmy"])); //true
console.log(mutation(["hello", "hey"])); //false
console.log(mutation(["voodoo", "no"])); //false
Check the working sample: https://jsfiddle.net/sayan751/3q8rtqy3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With