How can you make a break
of a Array.forEach
in JavaScript? When using a "for" loop in JavaScript the break
is used to break the loop.
From ECMA 5.1
appears the possibility of using Array.forEach
to iterate over array
, but how can you do a break
in this type of cycles?
Let's see two examples, where the attempt to interrupt the Array.forEach loop with "return"
does not give the expected result:
const firstElems_LenOne_V1 = (arr) => {
let rta = []
for (let i=0; i<arr.length;i++) {
let e=arr[i]
if (e.length>1) break
rta.push(e)
}
return rta
}
const firstElems_LenOne_V2 = (arr) => {
let rta = []
arr.forEach(e=>{
if (e.length==1) return // break forEach?
rta.push(e)
})
return rta
}
let v1= firstElems_LenOne_V1(["a","b","cc","d"])
let v2= firstElems_LenOne_V2(["a","b","cc","d"])
console.log(v1) // OK: expect [a,b] got [a,b]
console.log(v2) // KO: expect [a,b] got [cc]
How to do a break
inside an array.forEach in Javascript?
The forEach documentation has a note that there is no way to stop or kill a
forEach
unless it is aException
, if you want to do this the methodforEach
would not be appropriate. Instead they recommend using some() if you need to return a valueboleano
or just a simple iteration as in this case.custom exception
The method
Array.forEach
does not provide a system to stop the iteration. However you can use the functionArray.some
where you can returnfalse
to do just what you want.Example:
Result: