Search code examples
javascriptarraysconcatenationreduce

Concatenating arrays in Javascript


I am pretty new to javascript and I have an issue with flattening several arrays into one complete array using the reduce and concat function.

var array = [ [1, 3], [6, 6], [3, 3] ]; 

var finishedArray = function(array) {
var reducedArray = {};
var completeArray = {};


for (var i = 0; i < array.length; i++) {
    reducedArray[i] = array[i].reduce(function (a, b) {
        return a + b;
    });

    completeArray = reducedArray[i].concat(reducedArray[i + 1]);
}

return completeArray;

}

console.log(finishedArray(array));`

The error I get is : completeArray = reducedArray[i].concat(reducedArray[i + 1]);

TypeError: undefined is not a function

Why is that???


Solution

  • the easy way:

    var finishedArray = [ [1, 3], [6, 6], [3, 3] ].reduce(Function.apply.bind([].concat), [])
    

    another nice option than can be more readable is using a named function, which lets you apply this transform to many arrays in many places without so much ugly boilerplate every time:

    function flat(a,b){return a.concat(b);}
    
    [[1,3],[6,6],[3,3]].reduce(flat);
    [[7,3],[4,6],[8,1]].reduce(flat);
    

    it's the shortest path to flatten many different arrays.

    note you can also write the reusable in the same fast-but-ugly syntax as my first suggestion:

     var flat=Function.apply.bind([].concat);
    

    also note that elclanrs shows an even simpler method that i really like:

     [].concat.apply([],[[1,3],[6,6],[3,3]])