I needed to "convert" a simple flat array into a 2D array and I went on SO to see what it has to say about the argument.
I tried to recreate the code of this answer, and I got this error:
console.log(array.reduce((twoDArray, n, i) => (i % 3 == 0 ? twoDArray.push([n]) : twoDArray[twoDArray.length-1].push(n)), []));
^
TypeError: Cannot read property 'push' of undefined
The problem was that I didn't add && twoDArray
at the end of the arrow function. Here you can see:
let array = [1,2,3,4,5,6,7,8,9];
// this works
console.log(array.reduce((twoDArray, n, i) => (i % 3 == 0 ? twoDArray.push([n]) : twoDArray[twoDArray.length-1].push(n)) && twoDArray, []));
// here the second push() throws an error
console.log(array.reduce((twoDArray, n, i) => (i % 3 == 0 ? twoDArray.push([n]) : twoDArray[twoDArray.length-1].push(n)), []));
Now I don't understand a couple of things, namely:
- how does this
&& twoDArray
works? what's its purpose? - how can this addition fix the error when it is placed only after the
push()
that generates the error. Shouldn't the code throw an error before to reach the&&
?