Reputation: 437
I have a function that compares an array of 2 strings ... eg ['snookums', 'snook']
, which looks to return true if all of the letters in the 2nd string appear in the first, so in this instance, it should return true.
I have it working with a for loop:
function mutation(arr) {
for (var i = 0; i < arr[1].length; i++) {
if (arr[0].indexOf(arr[1][i]) === -1) {
return false;
}
}
return true;
});
}
However, I would like to get this working in a better way, ultimately with forEach. I have it console logging out false
if it comes across a letter which doesn't match, but I am wondering will this work, how will I return true
if it gets to the end of the forEach
and indexOf()
returns true
for each letter.
function mutation(arr) {
return arr.pop()
.split('')
.forEach(function(letter) {
console.log(arr[0].indexOf(letter) === -1);
});
}
console.log(mutation(["snookums", "for"]));
Does that make sense?
Thank you
Upvotes: 0
Views: 76
Reputation: 665545
forEach
is not a "better" way. What you are looking for is the every
method:
function mutation(arr) {
return arr[1].split("").every(function(letter) {
return arr[0].indexOf(letter) !== -1;
});
}
Upvotes: 5