Is there an easy way (like concat) to add an array to an array resulting in an array of arrays. For example, take these two arrays

var array1 = [1,2];
var array2 = [3,4];

and get....

var combineArray = [[1,2][3,4]];

?

share|improve this question
up vote 1 down vote accepted
var combinedArray = [array1, array2];
share|improve this answer
  • It would be that simple wouldn't it? Thanks, just learning to write my own custom functions for Google Sheets. – Michael 37 mins ago
  • @Michael you would have known that if you literally googled it the way you asked (concat arrays javascript). Anyway, if that answer is the solution to your question, please don't forget to mark Randy's answer as the answer so people know this question was answered =) – NoobishPro 35 mins ago
  • glad to help. Please accept my answer if you're satisfied. thanks! – Randy Casburn 35 mins ago
  • Additionally. can use Array.prototype.concat array1.concat(array2) – 멍개-mung 34 mins ago
  • I will accept it, I can't yet. @NoobishPro I thought concat was different. To my understanding, the result would have been [ 1, 2, 3, 4] using congat. Seriously, please correct me if I'm wrong. – Michael 25 mins ago

Try this one

var a = [1,2,'3','four'];
var b = [5,6];
var c = [a,b]; //Combine 2 arrays
console.log(c);

OR

var a = [1, 2, '3', 'four'];
var b = [5, 6];
var c = [a].concat([b]); //Combine 2 arrays
console.log(c);

share|improve this answer

Use the Array.prototype concat method provided by javascript

var array1 = [1,2];
var array2 = [3,4];
var combineArray = array1.concat(array2); //[1,2,3,4]
share|improve this answer

If you have two arrays and want to create an array of arrays you could write a simple function which takes an indefinite N number of arrays and reduces them to one array of N arrays.

E.g:

const combineArrays = ...arrays => arrays.reduce((acc, cur) => { acc.push(cur); return acc; }, []);

Edited for a simpler solution:

[].concat([array1, array2]);

If you want to flatten the two arrays, you can use ES6 destructuring synthax:

[...array1, ...array2]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.