3 Easy Ways to Merge Arrays in JavaScript

Here are three ways to merge arrays in JavaScript:

  1. Using Spread Operator(…)
  2. Using Array.prototype.concat()
  3. Using Array.prototype.push()

Method 1: Using the Spread Operator(…)

The spread operator(...) is used to expand or spread an iterable or an array. It allows us to copy all or part of an existing array into another array.

arr1 = ['hp', 'dell', 'mac'];
arr2 = ['lenovo', 'msi', 'asus'];
arr3 = ['Microsoft', 'LG', 'Acer'];

console.log([...arr1, ...arr2, ...arr3]);

Output

[
   'hp', 'dell',
   'mac', 'lenovo',
   'msi', 'asus',
   'Microsoft', 'LG',
   'Acer'
]

You can tell that the spread operator approach is a shortcut way to combine arrays as the code lines are reduced and easy to remember. Spread is excellent when you know beforehand that you are working with arrays.

Method 2: Using Array.prototype.concat()

The concat() method merges two or more two arrays. It returns a new array containing the joined arrays. It does not change an existing array.

arr1 = ['hp', 'dell', 'mac'];
arr2 = ['lenovo', 'msi', 'asus'];

console.log(arr1.concat(arr2));

Output

[ 'hp', 'dell', 'mac', 'lenovo', 'msi', 'asus' ]

You can see that the concat() function has combined an arr1 with the arr2 and gives us a combined array in the output.

Method 3: Using array.push()

The array push() method is used to push any value at the end of an array, and it can also be used to merge two arrays by pushing the values of the second array in the first array after the already present values.

arr1 = ['hp', 'dell', 'mac'];
arr2 = ['lenovo', 'msi', 'asus'];
arr3 = ['Microsoft', 'LG', 'Acer'];

let pushmethod = []
pushmethod.push(...arr1, ...arr2, ...arr3)
console.log(pushmethod)

Output

[
   'hp', 'dell','mac', 
   'lenovo','msi', 'asus',
   'Microsoft', 'LG','Acer'
]

In this example, we saw that we combined the push() method and spread operator to combine multiple arrays into one array.