Reputation: 81
Background
In Google Apps Script I would like to make a new array that combines two arrays vertically as columns, not as additional rows. I understand it's pretty easy to add additional rows using .concat or .push but this extends the array vertically.
Here's the code:
var ar1 = [[1,3,5],
[2,4,6]];
var ar2 = [[7,9,11],
[8,10,12]];
Desired Outcome
When running ar3 I would like the desired output to be:
[[1,3,5,7,9,11]
[2,4,6,8,10,12]]
Things I've Tried
I think this could be run as a function through concat. I have tried something like the below to no avail:
var ar3 = ar2.forEach(function (row){ ar1.concat([row[0],row[1],row[2]]); });
Could this be made even simpler with .map and return? (I know the below is very wrong, but just an example.)
var ar3 = ar1.map(function (row){ return ar1[row].concat(ar2[row]); });
Upvotes: 5
Views: 1658
Reputation: 13693
You can do it like this, without using concat:
var ar1 = [
[1, 3, 5],
[2, 4, 6]
];
var ar2 = [
[7, 9, 11],
[8, 10, 12]
];
const result = ar1.map((x, i) => [...x, ...ar2[i]]);
console.log('result', result)
Upvotes: 1