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

Time:11-29

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?

CodePudding user response:

You should use a for loop.

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

CodePudding user response:

If your goal is to continue running the loop until the condition is met, then you can nest your conditional logic inside a while loop and use a boolean flag to stop the loop from running.

Optionally, you could also use a break; now that a while loop is being used but a boolean flag works just as well without needing to rearrange your logic.

See notes within the snippet below:

var urlSet1 = new Map()
urlSet1.set('abc.com', 'def.com', 'ghi.net', 'jkl.com')

var urlSet2 = new Map()
urlSet2.set('abc.com', 'def.net', 'ghi.com', 'jkl.com')

var newUrl = ''

//set a boolean flag to use as condition for while loop
var running = true

//while running is true, continue running loop
while (running) {
  urlSet1.forEach(function(value) {
    if (urlSet2.has(value) == false) {
      newUrl = value;
      console.log(newUrl)
      //once condition is met, set boolean flag to false to stop loop
      running = false;
      console.log(running)
    } else {
      //some other condition
    }
  })
}

  • Related