DEV Community

Discussion on: [javascript] Array Partitioning by Length

Collapse
 
avalander profile image
Avalander

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:

const a = [ 1, 2, 3, 4 ]
groupInString(a, 2)
console.log(a)
Enter fullscreen mode Exit fullscreen mode

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.

const groupInString = (array, length) => {   
    const newArr = []
    for(let i = 0; i < array.length; i+= length) {
        newArr.push(
            array.slice(i, i + length).join('')              
        )
    }
    return newArr
}
Enter fullscreen mode Exit fullscreen mode