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?