How to Merge Arrays in JavaScript

Tram Ho

When working with arrays, there are times when you want to merge multiple arrays together, for example data comes from different sources and you have to merge them into one array, there are many ways to merge arrays in Javascript. I will show you 3 ways in this article.

1. Spread Operator

Using the spread operator allows you to spread an iterable collection (object or array) into another collection. Using this operator on arrays, you can merge values ​​of arrays together.

For the merged array, we create a new array and spread the values ​​of array1, then the values ​​of array2. You can use this with multiple arrays like this:

2. Array.concat

You can use array’s concat method to merge the values ​​of arrays together. Values ​​can be numbers, strings, booleans, objects, or even arrays.

By specifying an array as an argument, you can merge the original array with the specified array to form a new array. Here is an example:

You can also pass multiple arrays to concat like this:

3. Array.push

The push method of arrays allows you to push (add) values ​​to the end of the array.

Using this method, you can push a new array to the original array to perform the merge. Unlike the above approaches, this will change the original array.

Here we use a for loop to iterate over each value of array2, each time we push that value to the end of array1. At the end of the whole loop, we see that array1 has changed, it contains all the values ​​of array2.

Instead of using a for loop you can completely use the spread operator. The push method accepts a list or arguments separated by commas (comma), you can spread the array’s values ​​into this method and they will be pushed into the original array.

You can apply it to many different arrays:
Share the news now

Source : Viblo