How can we merge some arrays in JavaScript?
Old Way
Merge 2 Arrays
You can use concat to merge arrays.
ary1 = [1, 2]
ary2 = [2, 3]
ary1.concat(ary2)
// [ 1, 2, 2, 3 ]
Merge Multiple Arrays
concat
can take multiple arrays as arguments.
ary1.concat(ary2, [5, 6, 7])
// [ 1, 2, 2, 3, 5, 6, 7 ]
ES6 way
You can use Spread syntax to merge arrays in ES6(ES2015). This way is easier and more readable.
ary1 = [1, 2]
ary2 = [2, 3]
[...ary1, ...ary2]
// [ 1, 2, 2, 3 ]
You can merge multiple arrays as much as you want.
[...ary1, ...ary2, ...ary3]
Also, you can use combination of push and spread syntax.
ary1.push(...ary2)
console.log(ary1)
// [ 1, 2, 2, 3 ]
This changes ary1
value, so you should use this way when you want to merge another array into an array. In this case, ary2
is merged into ary1
.