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]];
?
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]];
?
var combinedArray = [array1, array2];
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);
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]
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]