Append Multi-Dimension Arrays Horizontally in Blocks

后端 未结 2 831
别跟我提以往
别跟我提以往 2021-01-29 08:28

I have several Multi-Dimension Arrays, that I wish to concatenate horizontally. Thinking of the Multi-Dimension Arrays as tables, I want to append each by stacking them horizont

相关标签:
2条回答
  • 2021-01-29 09:00

    You can use Array.push and spread syntax to achieve your solution.

    var arr1 = [["A1","B1","C1","D1"],["A2","B2","C2","D2"]]
    var arr2 = [["E1","F1","G1","H1"],["E2","F2","G2","H2"]]
    const output = []
    // if you know the maximum length you can provide yourself instead of Math.max(arr1.length, arr2.length)
    for(let i =0; i < Math.max(arr1.length, arr2.length); i++){
        //This will work even with different lengths of array
    	output.push([...(arr1[i] || []), ...(arr2[i] || [])])
    }
    console.log(output)

    P.S.: You can use other methods like map and reduce, but i am using for loop because in case of map the length of all arrays should be same.

    0 讨论(0)
  • 2021-01-29 09:08

    Here's a version with map.

    const arr1 = [["A1","B1","C1","D1"],["A2","B2","C2","D2"]]
    const arr2 = [["E1","F1","G1","H1"],["E2","F2","G2","H2"]];
    
    const out = arr1.map((arr, i) => {
      return arr.concat(arr2[i]);
    });
    
    console.log(out);

    0 讨论(0)
提交回复
热议问题