Languages
[Edit]
EN

JavaScript - add array to array

3 points
Created by:
Niac
508

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:

  1. Using the spread operator,
  2. 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.

 

References

  1. concat() - MDN Web Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - Arrays (popular problems)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join