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 available comes true.
5
Answers
ForEach doesn’t support break. use
for of
map
andforEach
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:
You can’t break the
forEach
.If you want to print only one item. I think the
find
method is what you are looking for.For more information:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
find
will short-circuit the iteration after it finds the first instance where the condition is met. You may want to put that code in its own function and then call it from the JSX.Note I’ve relabeled the
Book
property totitle
here as it made a little more sense semantically.I have faced the same issue earlier. I found that it is not possible to declare break in forEach or in map function. It will traverse the whole array instead. You can use break in for loop. However using a flag it can be done.
Reference:
Past Stack Overflow Post
MDN article: MDN article on ForEach()
However for loop will do that easily.
Such as:
This will give you the very first available which is true only. However you can also use find function to do get the same output: