1

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?

2
  • 2
    Is the first array an array of strings? are you missing double quotes? Commented Jul 10, 2015 at 7:11
  • Yes, sorry. Question edited! Commented Jul 10, 2015 at 8:20

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

@JosepBacardit What do you mean by that? Can you please create jsfiddle of the same
In the first array of the result, I want to add the first value of all arrays. In the second array result I want to add the second value of all arrays. Here an example: jsfiddle.net/drzkzaxL/1
1

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;
});

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.