How to Combine Arrays in JavaScript

To combine arrays in JavaScript, you can use the “Array.prototype.concat()” method. The concat() is a built-in method that merges two or more two arrays. It returns a new array containing the joined arrays. It does not change an existing array.

Syntax

Array.concat(array1, array2, array3,..., arrayX)

Parameters

  1. Array1 – The second array to be merged with “Array“.
  2. Array2 – The third array to be merged with “Array“.
  3. ArrayX – Nth array that is to be merged with “Array“.

Example

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. Now a question might arise, what if we want to combine more than two arrays in JavaScript. However, you can also see that it doesn’t modify or change the existing array.

Using a spread operator

The spread is a built-in JavaScript operator(...) used to expand or spread an iterable or an array. The spread operator allows us to copy all or part of an existing array into another array. The spread operator is often used in combination with destructuring.

Syntax

[… Array1, …Array2, …Array3, ..., ArrayN]

Arguments

  1. Array1   – It is the first array in which the rest arrays are to be combined.
  2. Array2  – It is the second array that is to be combined with the first array.
  3. ArrayN – It is the nth array to be combined with the first array.

Example

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.

Using the array.push() method

The array push() is a built-in JavaScript method 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.

Syntax

Array.push(…Array2, );

Arguments

Array – It is the first array in which the rest arrays are to be combined.

Array2 – It is the second array that is to be combined with the first array.

Example

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 in JavaScript.

Leave a Comment