3

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?

5
  • Because you can't concat array to 0 Commented Apr 4, 2017 at 10:25
  • The second (and optional) parameter of Array.prototype.reduce is the initial value. In your case, you're passing 0 as the initial value hence the first time the function runs it attempts to invoke prev.concat that would obviously fail because Number doesn't have a concat method. Commented Apr 4, 2017 at 10:26
  • What do you try to achieve with the second version of reduce? Commented Apr 4, 2017 at 10:27
  • thanks to all, i not have completely clear how reduce works yet Commented Apr 4, 2017 at 10:30
  • developer.mozilla.org/de/docs/Web/JavaScript/Reference/… Commented Apr 4, 2017 at 10:32

1 Answer 1

2

i not have completely clear how reduce works yet

It works like this:

Array.prototype.reduce = function(callback, startValue){
    var initialized = arguments.length > 1,
        accumulatedValue = startValue;

    for(var i=0; i<this.length; ++i){
        if(i in this){
            if(initialized){
                accumulatedValue = callback(accumulatedValue, this[i], i, this);
            }else{
                initialized = true;
                accumulatedValue = this[i];
            }
        }
    }

    if(!initialized)
        throw new TypeError("reduce of empty array with no initial value");
    return accumulatedValue;
}

Your failing example does pretty much this:

var array = [[1,2,3],[4,5,6],[7,8,9]];

var tmp = 0;
//and that's where it fails.
//because `tmp` is 0 and 0 has no `concat` method
tmp = tmp.concat(array[0]);
tmp = tmp.concat(array[1]);
tmp = tmp.concat(array[2]);

var new_array = tmp;

replace the 0 with an Array, like [ 0 ]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.