Search code examples
javascriptarraysmultidimensional-arrayecmascript-6array-merge

Merge multiple two-dimensional arrays into one two-dimesional array in javascript


How do you combine these arrays into one merged array? The data is from a table with rows and columns.

One array contains data of an entire single column.

I would like to merge these columns into one array with 3 columns.

//array from col 1
let firstArray = [
    [100],      //row 1, col 1
    [200],      //row 2, col 1
    [300]       //row 3, col 1
]

//array from col 2
let secondArray = let firstArray = [
    ['a'],      //row 1, col 2
    ['b'],      //row 2, col 2
    ['c']       //row 3, col 2
]

//array from col 2
let secondArray = let firstArray = [
    ['run'],        //row 1, col 3
    ['hide'],       //row 2, col 3
    ['seek']        //row 3, col 3
]

Expected merged array output:

let mergedArray = [
    [100, 'a', 'run'],      //row 1, col 123
    [200, 'b', 'hide'],     //row 2, col 123
    [300, 'b', 'seek']      //row 3, col 123
]

Solution

  • const firstArray = [
        [100],      //row 1, col 1
        [200],      //row 2, col 1
        [300]       //row 3, col 1
    ];
    const secondArray = [
        ['a'],      //row 1, col 2
        ['b'],      //row 2, col 2
        ['c']       //row 3, col 2
    ];
    const thirdArray = [
        ['run'],        //row 1, col 3
        ['hide'],       //row 2, col 3
        ['seek']        //row 3, col 3
    ];
    
    const mergedArray = firstArray.map((item1, i) => {
      const item2 = secondArray[i];
      const item3 = thirdArray[i];
      return [item1[0], item2[0], item3[0]];
    });
    console.log(mergedArray);