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 4 hours 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 4 hours ago
  • Additionally. can use Array.prototype.concat array1.concat(array2) – 멍개-mung 4 hours 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 4 hours ago
  • @Michael no, you're actually right... But if you google it, it brings you to an explanation of the function with examples and it warns you about that. Then it also shows examples of what to do to achieve what you wanted to right now, also giving links to those. It's just really, really easy to google is all I mean. You could literally google "array array array javascript" and you'd find your answer. – NoobishPro 4 hours 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

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

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

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.