javascript

Combine or merge two or multiple arrays into single array in Javascript

If you want to merge two or more arrays into single array then you can use below code methods in Javascript.

const users1 = ['Ankit', 'Gaurav'];
const users2 = ['Abadhesh', 'Sourabh'];
const users3 = ['Arun', 'Avinash'];

//FIRST METHOD - using ...
const all_users1 = [...users1, ...users2, ...users3];

//SECOND METHOD - using .concat()
const all_users2 = users1.concat(users2).concat(users3)

Output

["Ankit","Gaurav","Abadhesh","Sourabh","Arun","Avinash"]

In the first method to merge or concatenate two or multiple arrays we are using ... before the variable name that consist the array. In the code snippet, we have three arrays - users1, users2, users3. And we want to combine them in single Array.

# Code Example 2 - Use concat() with spread operator to join multiple arrays

const arr1 = [10, 20, 30];
const arr2 = [40, 50, 60];
const arr3 = [70, 80];

const result = [].concat(...[arr1, arr2, arr3])

console.log(result);

Output

[10,20,30,40,50,60,70,80]

Try it yourself

First Method - Using ... before array const

We are using ... before const name of array and then making a new array using them. The syntax for this can be as below.

[...arr1, ...arr2, ...arr3];

Live Demo of First Method:

Second Method - Using Array.concat() method

We can also use Array.concat() method to combine multiple arrays into single one. The syntax for this can be as below.

arr1.concat(arr2)

Live Demo:

Was this helpful?