Why does the following log [1,2,3,4] and not [[1],[2],[3],[4]]?
function steamrollArray(arr) {
console.log([].concat(...arr));
}
steamrollArray([[1], [2], [3], [4]]);
Why does the following log [1,2,3,4] and not [[1],[2],[3],[4]]?
function steamrollArray(arr) {
console.log([].concat(...arr));
}
steamrollArray([[1], [2], [3], [4]]);
Why do you expect the above code to return [[1],[2],[3],[4]]
?
The Spread operator will expand the elements of the 2D array. So ...arr
will be [1] [2] [3] [4]
Then you are essentially doing [].concat([1] [2] [3] [4])
.
So if you were to do a naive implementation yourself, it would look like so
[].concat([1]).concat([2]).concat([3]).concat([4])
Which results in
[1]
[1,2]
[1,2,3]
[1,2,3,4]
for each function call respectively.
I expected this because my brain no good. Thank you