I'm working on an exercise where, starting from an array of arrays, I have to reduce it (using reduce and concat) in a single array that contains all the elements of every single arrays given.
So I start from this:
var array = [[1,2,3],[4,5,6],[7,8,9]]
And I solved the exercise with this:
var new_array = array.reduce(function(prev,cur){return prev.concat(cur);})
So it works, typing console.log(new_array) I have this:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
But if I modify the function in this way:
var new_array = array.reduce(function(prev,cur){return prev.concat(cur);},0)
I get this error:
"TypeError: prev.concat is not a function
Why I get this error?
Array.prototype.reduceis the initial value. In your case, you're passing0as the initial value hence the first time the function runs it attempts to invokeprev.concatthat would obviously fail becauseNumberdoesn't have aconcatmethod.