1

I have a this loops

for (var key in params) {
  if (Array.isArray(params[key])) {
    params[key].every(function(item) {
      let value = something(item.start, item.end);
      if (value === item.start || value == item.end) {
        return false // break
      }
    })
  }
}

When i set return false to stop the every() function i also want to stop the first loop. How can i do that? I tried this:

OUTER_LOOP: for (var key in params) {
  if (Array.isArray(params[key])) {
    params[key].every(function(item) {
      let value = something(item.start, item.end);
      if (value === item.start || value == item.end) {
        return false // break
        break OUTER_LOOP; // not working
      }
    })
  }
}

but it doesn't work in this way... so how can i stop the every() function and the first loop at same time correctly?

1
  • can you share the content of param Commented Oct 20, 2020 at 13:08

1 Answer 1

1

You could take Array#some and return true for exit some and use the returned value of some for breaking the loop.

for (var key in params) {
    if (Array.isArray(params[key])) {
        const
            leave = params[key].some(item => {
                let value = something(item.start, item.end);

                // exit condition should return true/truthy value
                // for leaving the outer loop
                return value === item.start || value == item.end;
            });

        if (leave) break;
    }
}
Sign up to request clarification or add additional context in comments.

8 Comments

thanks, but return true doesn't stop the for (var key in params) loop
yes, please see edit. the result needs to bubbled outside with a check.
thank you, I have updated my code again, because I forgot something... does it still work with some()? could you take a look again?
thanks for you update. But i have one problem. something() returns for e.g. a float value like 0.99 if the item.end is 1 so the loops ends before 1 so in my console.log() i see it ends with 0.99 instead of 1. How can i change the if condition, so i can also see 1 once and then the loop breaks? or do i need to pass my other stuff before return value ?
you could round the value ...?
|

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.