[Solved] merge n arrays in one multidimensional in javascript [closed]


This is what I came up with:

First calculate the longest array.

Then loop over the arrays, and loop over the items.

Here’s a fiddle

var a = [ 'a1', 'a2' ],
    b = [ 'b1', 'b2' ],
    c = [ 'c1', 'c2', 'c3' ];



var to2DArray = function(){
    var maxLength = 0,
        arrays = arguments;
        resultArray = [];
    for(var i = 0; i< arrays.length; i++){
        if(arrays[i].length > maxLength) maxLength = arrays[i].length;
    }
    for(var j = 0; j < maxLength; j++){
        var subArray = [];
        for(var i = 0; i< arrays.length; i++){
            if(arrays[i][j] !== undefined) subArray.push(arrays[i][j]);
        }
        resultArray.push(subArray);
    }
    return resultArray;
}

console.log(to2DArray(a, b, c)); //resulting in: [["a1","b1","c1"],["a2","b2","c2"],["c3"]] 

solved merge n arrays in one multidimensional in javascript [closed]