How can I merge two arrays in JavaScript?
Antek N
antek n profile pic

In JavaScript, there are several ways to merge two arrays into a single array. Let's explore some common methods: 1. Using the concat() method: Theconcat() method is used to merge two or more arrays and create a new array as a result. You can pass the arrays to be merged as arguments toconcat() to create a new array that contains all elements from both arrays. Here's an example:

1
2
3
4
5
6

   var array1 = [1, 2, 3];
   var array2 = [4, 5, 6];
   var mergedArray = array1.concat(array2);
   console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
   

In this code snippet,concat() is called onarray1 and passedarray2 as an argument. The result is a new array (mergedArray) that contains all elements from botharray1 andarray2. 2. Using the spread operator: ES6 introduced the spread operator (...), which allows you to expand elements from an array or other iterable objects. You can use the spread operator to merge arrays by spreading the elements of each array into a new array. Here's an example:

1
2
3
4
5
6

   var array1 = [1, 2, 3];
   var array2 = [4, 5, 6];
   var mergedArray = [...array1, ...array2];
   console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
   

In this code snippet, the spread operator is used to spread the elements ofarray1 andarray2 into a new array (mergedArray), effectively merging the arrays. 3. Using the push() method: If you want to merge one array into another in-place, you can use thepush() method to add elements from one array to the end of another array. Here's an example:

1
2
3
4
5
6

   var array1 = [1, 2, 3];
   var array2 = [4, 5, 6];
   Array.prototype.push.apply(array1, array2);
   console.log(array1); // Output: [1, 2, 3, 4, 5, 6]
   

In this code snippet, theapply() method is used to invokepush() onarray1 and passarray2 as the argument. This adds all elements fromarray2 to the end ofarray1, effectively merging the arrays. These are some common approaches to merge two arrays into a single array in JavaScript. Choose the method that best suits your coding style and requirements. Keep in mind that the first two methods create a new merged array, while the third method modifies one of the original arrays.