Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: exercise with concat and reduce

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?

like image 371
Giacomo Ciampoli Avatar asked Sep 21 '26 02:09

Giacomo Ciampoli


1 Answers

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 ]

like image 85
Thomas Avatar answered Sep 23 '26 16:09

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!