How to Merge Arrays in JavaScript
Merging arrays in JavaScript is a common task and can be accomplished in several ways depending on your needs. Here are some of the most common methods:
1. Using the concat()
Method
The concat()
method creates a new array by combining multiple arrays.
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = array1.concat(array2);
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
2. Using the Spread Operator (...
)
The spread operator is a more modern and concise way to merge arrays.
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = [...array1, ...array2];
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
3. Using Array.prototype.push()
with the Spread Operator
If you want to merge arrays into an existing array, you can use push()
with the spread operator.
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
array1.push(...array2);
console.log(array1); // Output: [1, 2, 3, 4, 5, 6]
4. Using Array.prototype.unshift()
with the Spread Operator
Similarly, if you want to merge arrays at the beginning of an existing array, use unshift()
with the spread operator.
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
array1.unshift(...array2);
console.log(array1); // Output: [4, 5, 6, 1, 2, 3]
5. Using Array.prototype.reduce()
For more complex merging scenarios, such as merging multiple arrays dynamically, reduce()
can be useful.
const arrays = [
[1, 2],
[3, 4],
[5, 6],
];
const mergedArray = arrays.reduce((acc, curr) => acc.concat(curr), []);
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
6. Using Array.prototype.flat()
If you have nested arrays and want to merge them into a single array, flat()
can help.
const nestedArrays = [1, [2, [3, 4]], 5];
const mergedArray = nestedArrays.flat(2); // The argument specifies the depth to flatten
console.log(mergedArray); // Output: [1, 2, 3, 4, 5]
Each of these methods has its use cases, so you can choose the one that best fits your needs for merging arrays.