简体   繁体   中英

Concatenate Arrays -how to concat two dimensional arrays in javascript?

I have the following two arrays in JavaScript:

var array1=[[6, 12, 18],[7, 13, 19],[6, 12, 18],[7, 13, 19],[6, 12, 18],[6, 12, 18]];
var array2=[0,1,2,3,4,5]; 

How to concat the above arrays such that each element of array2 gets inserted at the end of each array1. The result should be such that

var merge array=[[0, 6, 12, 18],[1, 7, 13, 19],[2, 6, 12, 18],[3, 7, 13, 19],[4, 6, 12, 18],[5, 6, 12, 18]]

 var array1=[[6, 12, 18],[7, 13, 19],[6, 12, 18],[7, 13, 19],[6, 12, 18],[6, 12, 18]]; var array2=[0,1,2,3,4,5]; var merged_array = array1.map(function (value, index) { value.unshift(array2[index]); return value; }); alert(JSON.stringify(merged_array)); 

var array1=[[6, 12, 18],[7, 13, 19],[6, 12, 18],[7, 13, 19],[6, 12, 18],[6, 12, 18]];
var array2=[0,1,2,3,4,5];

$.each(array1,function(index,val){
   val.unshift(array2[index]);
});

Something like this should do it. Note this depends on your arrays being of the same length.

for (var i = 0; i < array2.length; i++)
{
   array1[i].unshift(array2[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM