EN
JavaScript - add array to array
3
points
In this article, we would like to show you how to add array to array in JavaScript.
There are two most common ways how to add an array to an array:
- Using the spread operator,
- Using
concat()
method.
1. Spread operator example
The below example shows how to use the spread operator (...
) to create a new array3
object which is a combination of two arrays.
// ONLINE-RUNNER:browser;
const array1 = ['1', '2'];
const array2 = ['3', '4'];
const array3 = [...array1, ...array2]
console.log(array3); // 1,2,3,4
2. concat()
method example
We can use the method on an empty array []
and pass two arrays we want to merge as arguments.
Runnable example:
// ONLINE-RUNNER:browser;
const array1 = ['1', '2'];
const array2 = ['3', '4'];
const array3 = [].concat(array1, array2);
console.log(array3); // 1,2,3,4
We can also use concat()
method on the existing array and pass just one argument - the array we want to merge our base array with.
Runnable example:
// ONLINE-RUNNER:browser;
const array1 = ['1', '2'];
const array2 = ['3', '4'];
const array3 = array1.concat(array2);
console.log(array3); // 1,2,3,4
Merging arrays in different order example:
// ONLINE-RUNNER:browser;
const array1 = ['1', '2'];
const array2 = ['3', '4'];
const array3 = [].concat(array2, array1);
const array4 = array2.concat(array1);
console.log(array3); // 3,4,1,2
console.log(array4); // 3,4,1,2
Note:
concat()
doesn't change existing array.