Search code examples
javascriptarraysset

How to loop through a JS set and break when a value is found?


I have 2 sets of URLs. I want to loop through one set and compare each value with .has to the 2nd set.

To that effect I have:

  urlSet1.forEach(function(value) {
    if (urlSet2.has(value) == false) {
      newUrl = value;
      return false;
    }
  })

However, of course, this keeps continuing to loop through.

I tried using every but I get the error:

urlSet1.every is not a function

And of course break; does not work on this either.

Would anyone know how to achieve this?


Solution

  • You should use a for loop.

    for (const url of urlSet1) {
      if (!urlSet2.has(url)) {
        newUrl = url;
        break;
      }
    }