I don't really understand how forEach is supposed to help here, the thing is that you are using Array.prototype.splice, which mutates the original array.
If you run this code:
consta=[1,2,3,4]groupInString(a,2)console.log(a)
You'll see that your function, besides returning the array [ '12', '34' ] mutated a into [ null, null ] as a side effect, which is inconvenient if somebody intended to use that array in several operations.
It is a lot better if functions return new values without modifying the input values. Without making big changes, you can fix your function not to modify the input array by using slice instead of splice.
I don't really understand how
forEach
is supposed to help here, the thing is that you are using Array.prototype.splice, which mutates the original array.If you run this code:
You'll see that your function, besides returning the array
[ '12', '34' ]
mutateda
into[ null, null ]
as a side effect, which is inconvenient if somebody intended to use that array in several operations.It is a lot better if functions return new values without modifying the input values. Without making big changes, you can fix your function not to modify the input array by using slice instead of splice.