How to Merge Two Arrays in JavaScript: Simple Methods
You can merge two arrays in JavaScript using the
concat() method or the spread operator .... Both combine arrays into a new one without changing the original arrays.Syntax
There are two common ways to merge arrays:
- Using
concat():newArray = array1.concat(array2)combinesarray1andarray2into a new array. - Using spread operator
...:newArray = [...array1, ...array2]spreads elements of both arrays into a new array.
javascript
const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; // Using concat const merged1 = array1.concat(array2); // Using spread operator const merged2 = [...array1, ...array2];
Example
This example shows how to merge two arrays using both methods and prints the results.
javascript
const fruits = ['apple', 'banana']; const vegetables = ['carrot', 'lettuce']; // Merge using concat const food1 = fruits.concat(vegetables); console.log('Using concat:', food1); // Merge using spread operator const food2 = [...fruits, ...vegetables]; console.log('Using spread operator:', food2);
Output
Using concat: [ 'apple', 'banana', 'carrot', 'lettuce' ]
Using spread operator: [ 'apple', 'banana', 'carrot', 'lettuce' ]
Common Pitfalls
Some common mistakes when merging arrays:
- Modifying original arrays instead of creating a new one.
- Using
push()with arrays directly, which adds the whole array as one element. - Confusing array merging with string concatenation.
Always use concat() or spread operator to get a new merged array.
javascript
const arr1 = [1, 2]; const arr2 = [3, 4]; // Wrong: pushes arr2 as a single element arr1.push(arr2); console.log(arr1); // Output: [1, 2, [3, 4]] // Right: merge with spread operator const merged = [...arr1, ...arr2]; console.log(merged); // Output: [1, 2, 3, 4]
Output
[1, 2, [3, 4]]
[1, 2, 3, 4]
Quick Reference
| Method | Description | Example |
|---|---|---|
| concat() | Returns a new array by joining two arrays | newArray = arr1.concat(arr2) |
| Spread operator | Creates a new array by spreading elements of arrays | newArray = [...arr1, ...arr2] |
Key Takeaways
Use
concat() or spread operator ... to merge arrays without changing originals.Avoid using
push() to merge arrays as it nests arrays inside.Both methods create a new array with elements from both arrays combined.
Spread operator is concise and works well in modern JavaScript.
Remember original arrays stay unchanged after merging.