Search code examples
javascriptarraystypescriptmapreducearray-map

Javascript/Typescript: Generate new arrays from other arrays with map / reduce?


I'm going nuts since two days with this problem.

I have an array of arrays, like this ( the number of the arrays can change, also the count of their elements, but to get the thing behind let's assume this example):

array = [ ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"], ["19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36"], ["37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54"] ];

All I want is to create a new array with some arrays within which look like that:

result = [ ["1", "19", "37"], ["2", "20", 38"], ... ];

I got this working with some foreach-loops, but I want to know how to do this with map() and reduce(). I tried and got some results, but far away from what I need.

Can someone please give me a helping hand for that?

Thanks in advance, Cheers


Solution

  • You could iterate the arrays and change the outer i and inner j index for assigning the actual value.

    //                                                v--------v------v
    result = array.reduce((r, a, i) => (a.forEach((v, j) => (r[j] = r[j] || [])[i] = v), r), []);
    //                           ^----------------------------------------------^
    

    var array = [["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"], ["19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36"], ["37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54"]],
        result = array.reduce((r, a, i) => (a.forEach((v, j) => (r[j] = r[j] || [])[i] = v), r), []);
        
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    With explicit check and assignment of an empty array.

    var array = [["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"], ["19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36"], ["37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54"]],
        result = array.reduce((r, a, i) => {
            a.forEach((v, j) => {
                if (!(j in r)) {
                    r[j] = [];
                }
                r[j][i] = v;
            });
            return r;
        }, []);
        
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }