Home > other >  Break the foreach method when the value comes true
Break the foreach method when the value comes true

Time:12-27

I have to break the forEach method when the value of available is true.

[
  {
    "Book": "Book1",
    "available": false
  },
  {
    "Book": "Book2",
    "available": false
  },
  {
    "Book": "Book3",
    "available": true
  },
  {
    "Book": "Book4",
    "available": true
  }
]

And print only one item after the value of availble comes true.

CodePudding user response:

map and forEach will run on all values in the array. There is a loop under the hood, but you don't have control over the loop body.

If you want to break at some position in the loop, just use a for-of loop:

for (const book of books) {
    if (book.available) break;
}

CodePudding user response:

ForEach doen's support break. use for of

for (const el of arr) {
   if (el.available) {
    break;
  }
}
  • Related