Chrome Extension

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)
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool
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.

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?
0 Comments