In this article we will learn how to merge two arrays in JavaScript.
It is very common to merge two arrays in JavaScript in JavaScript.
Problem
Now we have a problem, which is that we want to merge two or more arrays together.
Imagine we have two arrays like those:
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
And we want to combine those two arrays so that the result will be like this:
[1, 2, 3, 4, 5, 6];
How to solve this problem?
Well, this problem is easy to solve, and there's more than one solution to solve this problem such as:
- Using spread operator
...
- Using
concat
method - Using
forEach
Merge two arrays using spread operator
As we said before, we can use spread operator ...
to merge two or more arrays.
Example
// Arrays
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
// Merge
const merge = [...array1, ...array2];
// Result:
console.log(merge);
Output
[ 1, 2, 3, 4, 5, 6 ]
The spread (...) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. (Source: MDN)
Merge two arrays using concat
method
We can use Array.concat
to merge two arrays as well.
// Arrays
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
// Merge
const merge = array1.concat(array2);
// Result:
console.log(merge);
Output
[ 1, 2, 3, 4, 5, 6 ]
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. (Source: MDN)
Merge two arrays using forEach
We can iterate on an array and then add all its elements to the other array, but this method will only work for two arrays together, but more than that it will be very complicated.
Example
// Arrays
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
// Iterate over `array2`
array2.forEach(ele => {
// Add `array2` elements to `array1`
array1.push(ele);
});
// Print result:
console.log(array1);
Output
[ 1, 2, 3, 4, 5, 6 ]
Thank you for reading
Thank you for reading my blog. 🚀