Skip to content
Advertisement

Break the foreach method when the value comes true

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
  }
]

enter image description here

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

Advertisement

Answer

ForEach doen’s support break. use for of

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