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]
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:
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:
0 Comments