简体   繁体   中英

Concatenate multiple arrays in a array of strings

I have this multiple array:

var array = [["par0_0","par0_1","par0_2"],["par1_0","par1_1","par1_2"],["par2_0","par2_1","par2_2"]];

I would like to transform this array in the following array of strings:

var result = [["par0_0,par1_0,par2_0"],["par0_1,par1_1,par2_1"],["par0_2,par1_2,par2_2"]];

What is the most efficient way?

You can use toString() on array to convert the array values to string and concat them.

 var myArr = [ ['par0_0', 'par0_1', 'par0_2'], ['par1_0', 'par1_1', 'par1_2'], ['par2_0', 'par2_1', 'par2_2'] ]; var myArrLen = myArr.length, myOutput = []; // The output array for (var i = 0; i < myArrLen; i++) { var arrEl = []; // Initialize the array for inserting sub-array for (var j = 0; j < myArr[i].length; j++) { arrEl.push(myArr[j][i]); // Add items from same column into sub-array } myOutput[i] = [arrEl.toString()]; // Assign the string to output array } document.write(myOutput); console.log(myOutput); 

jsfiddle Demo

You can also use reduce() function twice

[par0_0, par0_1, par0_2].reduce(function(previousValue, currentValue, index, array) {
   var result = "";
   if (index != 0)
   {
      result = ",";
   }
   return result + previousValue + currentValue;
});

You can use join() . Here is an example:

var arr = [["par0_0","par0_1","par0_2"],
["par1_0","par1_1","par1_2"],
["par2_0","par2_1","par2_2"]]

for(var i = 0 ; i < arr.length; i++) {
    arr[i] = [arr[i].join()] ;
}

join() accepts an optional separator argument if you do not want to commas. Default separator is comma.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join

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