0
function checkMagazine(magazine, note) {
    var map = new Map();
    var noteAr = note.split(" ");
    var magazineAr = magazine.split(" ")

    noteAr.forEach((note) => {
        if (map.has(note)) {
            map.set(note, map.get(note) + 1)
        } else {
            map.set(note)
        }
    });

    magazineAr.forEach((word) => {
        if (!map.has(word)) {
            return "No"
        }
    });

    return "Yes"
}

I'm checking to see if each word of a note is contained in the magazine by first hashing the values of the note and checking them in magazineAr. If the note word does not exist in the hash, then I am return "NOing. However, I keep getting a return "YES" in console.
I've watched it in debugger mode and I see it enter the statement where it hits 'return No' but then it just keeps on going with the forEach loop. I've even tried return false but same thing.

user10108817
  • 285
  • 1
  • 3
  • 11

1 Answers1

3

A forEach callback ignores the value that's returned - no matter what it is, every item in the array will be called with the forEach. For what you're trying to do, you should probably use every instead, which checks whether all items in the array fulfill the condition:

const hasEveryWord = magazineAr.every(word => map.has(word));
return hasEveryWord
  ? "Yes"
  : "No";
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320