2016-12-01 236 views
0

我有2個二維數組(array1和array2),它們是兩個表,每個都有5列。添加colums形成一個二維數組到另一個二維數組

我需要通過以獲得一個ARRY是與10列

表添加列形式陣列2編輯ARRAY1

例如:

array1 [1,1,1,1,1] 
     [2,2,2,2,2] 
     [3,3,3,3,3] 

array2 [a,a,a,a,a] 
     [b,b,b,b,b] 
     [c,c,c,c,c] 

new array1 [1,1,1,1,1,a,a,a,a,a] 
      [2,2,2,2,2,b,b,b,b,b] 
      [3,3,3,3,3,c,c,c,c,c] 

Thnak的很多關於任何意見

回答

1

您可以迭代並使用Array#splice來連接其他值。

var array1 = [[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3]], 
 
    array2 = [['a', 'a', 'a', 'a', 'a'], ['b', 'b', 'b', 'b', 'b'], ['c', 'c', 'c', 'c', 'c']]; 
 

 
array1.forEach(function (a, i) { 
 
    Array.prototype.splice.apply(a, [a.length, 0].concat(array2[i])); 
 
}); 
 

 
console.log(array1);

+0

謝謝很多,它工作得很好,我自己嘗試了forEach函數,但似乎我無法拿出一個工作代碼。非常感謝! – d4rk5h4rk

0

的情況下,兩個數組有相同的長度,那麼你可以放心地使用這個

var arr1 = [[1,2,3], [4,5,6], [7,8,9]]; 
var arr2 = [["a","b","c"], ["d","e","f"], ["g","h","i"], ["j", "k","l"]]; 

var narr = []; 
for(var ii = 0, len = Math.min(arr1.length, arr2.length); ii < len; ii++) { 
    narr[ii] = arr1[ii].concat(arr2[ii]); 
} 

,長度等於最小長度,這將創建一個新的數組兩個陣列arr1 & arr2

的結果將是:

[1,2,3,"a","b","c"] 
[4,5,6,"d","e","f"] 
[7,8,9,"g","h","i"] 

,如果你不知道它們具有相同的長度,你可以簡單地改變這段代碼

var arr1 = [[1,2,3], [4,5,6], [7,8,9]]; 
var arr2 = [["a","b","c"], ["d","e","f"], ["g","h","i"], ["j", "k","l"]]; 

var narr = []; 
for(var ii = 0, len = Math.max(arr1.length, arr2.length); ii < len; ii++) { 
    narr[ii] = arr1[ii] ? arr1[ii].concat(arr2[ii]) : arr2[ii]; 
} 

結果將是

[1,2,3,"a","b","c"] 
[4,5,6,"d","e","f"] 
[7,8,9,"g","h","i"] 
["j","k","l"] 
+0

謝謝!既然你正確地質疑數組的相同長度,我有一個更復雜的問題^ _^....你認爲在連接之前匹配一個列的2個數組可能是可能的嗎? (像SQL連接功能) – d4rk5h4rk

+0

@用戶歡迎..我沒有得到你的意思? –

相關問題