0

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

0

1 Answer 1

5

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;
    });
}
Sign up to request clarification or add additional context in comments.

2 Comments

Nice, so this will only return true if every element finds a match?
Exactly, it returns true iff the predicate returns true for every element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.