0

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]];

?

Eddie
  • 26,593
  • 6
  • 36
  • 58

4 Answers4

1
var combinedArray = [array1, array2];
Randy Casburn
  • 13,840
  • 1
  • 16
  • 31
  • It would be that simple wouldn't it? Thanks, just learning to write my own custom functions for Google Sheets. – Michael Feb 20 '18 at 03:10
  • @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 Feb 20 '18 at 03:11
  • Additionally. can use ```Array.prototype.concat``` ```array1.concat(array2)``` – 멍개-mung Feb 20 '18 at 03:13
  • 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 Feb 20 '18 at 03:21
  • @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 Feb 20 '18 at 03:26
1

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);
iLyas
  • 1,047
  • 2
  • 13
  • 30
0

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]
izengod
  • 1,116
  • 5
  • 17
  • 41
0

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]
Lucas Lago
  • 146
  • 6