在块中水平附加多维数组

时间:2019-01-12 12:57:39

标签: javascript multidimensional-array

我有几个多维数组,希望将它们水平连接。将多维数组视为表,我想通过水平堆叠将它们追加。

我尝试使用地图和嵌套地图,但是我无法使其完全按照所述方式工作。

var arr1 = [["A1","B1","C1","D1"],["A2","B2","C2","D2"]]
var arr2 = [["E1","F1","G1","H1"],["E2","F2","G2","H2"]]

我如何将它们合并到输出将是一个单独的数组中

var arrMerged = [["A1","B1","C1","D1","E1","F1","G1","H1"],["A2","B2","C2","D2","E2","F2","G2","H2"]]

2 个答案:

答案 0 :(得分:0)

这里是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);

答案 1 :(得分:0)

您可以使用Array.push和传播语法来实现您的解决方案。

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 .:您可以使用其他方法,例如map和reduce,但我使用的是for循环,因为在使用map的情况下,所有数组的长度应相同。