5 ways to merge arrays in JavaScript and their differences
You may need to merge one or more arrays in JavaScript. Please read this article to learn how to do it with related usages and differences.
An array
is a collection of elements or items. We use arrays to store data as elements and retrieve them back when we need them. The array is a data structure widely used in many programming languages, and JavaScript is not an exception.
You may need to merge one or more arrays to combine all the elements from the individual arrays into one array. We face this need when we have data coming from different streams, and we want to merge them into one data structure.
In this article, we will learn five different ways to merge arrays in JavaScript. We will also conclude which is the best way among all and when to use it.
If you like to learn from video content as well, this article is also available as a video tutorial here: ๐
Please feel free to subscribe for the future content
Alright, let's get started.
1. Using the traditional for
loop
Using the for
loop to merge two or more array elements may be the most viable way. Most of us are aware of how to use for-loops in programming. So it is the easiest option to start with. However, it may not be the best solution for the problem at hand.
To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push()
method) to another array.
Here is a JavaScript function doing the same,
const merge = (first, second) => {
for(let i=0; i<second.length; i++) {
first.push(second[i]);
}
return first;
}
Now, we can call the merge()
function and pass two arrays as the arguments for merging.
merge([1,2,3], [4,5,6]);
As we expected, here is the output of the merged array,
Alright, but how do we merge more than two arrays using the same merge()
function? Well, it may not be a very friendly way but, we can do something like this,
merge(merge([1,2,3], [4,5,6]), [7,8,9]);
So here, we first merge two arrays and merge the output of it with another array.
As you can guess, as our requirement of the number of input arrays grows for merge, it will be a lesser friendly way to manage it. So, using the for-loop to merge two or more arrays is fine, to begin with, but may not be an excellent method to use in practice.
2. Using the Spread
operator
Since ES6, we can use the ...
(yes, three consecutive dots) as a spread operator to destructure arrays. We can use the spread operator on arrays within an array literal([]
) to merge them. Let's see it with an example.
First, we will take two arrays, arr1
and arr2
. Then merge the arrays using the spread operator(...
) within an array literal.
const arr1 = [1,2,3];
const arr2 = [4,5,6];
// Merge arrays
const merged = [...arr1, ...arr2];
console.log(merged); // [1,2,3,4,5,6]
console.log(arr1); // [1,2,3]
console.log(arr2); // [4,5,6]
Now, notice the output of the merge. The arrays arr1
and arr2
are merged, and their elements are combined into a new
array. Please note, the input arrays are not changed here.
Ok, so how do we merge more than two arrays using this method? Easy, pass as many arrays you want to merge as comma-separated.
const arr1 = [1,2,3];
const arr2 = [4,5,6];
const arr3 = [7,8,9];
// Merge arrays
const merged = [...arr1, ...arr2, ...arr3];
console.log(merged); // [1,2,3,4,5,6,7,8,9]
This way of merging arrays is much convenient than using the traditional for-loop approach we have seen before. It is a go-to way to merge arrays in JavaScript except for a tiny gotcha that we will see in a while!
3. Using the concat()
array method
JavaScript Array
object has several practical methods. One of them is the concat()
method. The primary usage of the concat method is to merge two arrays.
const arr1 = [1,2,3];
const arr2 = [4,5,6];
// Merge arrays
const merged = arr1.concat(arr2);
console.log(merged); // [1,2,3,4,5,6]
console.log(arr1); // [1,2,3]
console.log(arr2); // [4,5,6]
In the above code, we merge two arrays using the concat()
method. However, it is not my favorite syntax in merging arrays. We may misinterpret The syntax arr1.concat(arr2)
as we are merging arr2
's element into arr1
and changing the array1 array itself. That's not the fact, though.
Like we used the spread
operator, the concat
method will not change the input arrays. Rather, it creates a new array merging all the input arrays and returns it. So, a better way of writing the concat()
method to merge arrays is,
const merged = [].concat(arr1, arr2);
Here, it is clear that we can concat multiple arrays to an empty array and return the merged array as a result. You can pass as many arrays as input arguments to the concat()
method.
Great, but which one to use? The spread
operator or the concat()
method?
If you are sure the inputs are all arrays, please use the spread
operator. It is a very straightforward and modern way to merge arrays. But if you are unsure about the input element type, use the concat()
method.
For example, let's take a string tapas
and use the spread operator on it with the array literals,
[...'tapas']
What do you think the output will be? The string tapas
will be destructured into an array of characters it is made of,
So, when you merge it with other arrays, the final result may not be the one you were expecting,
const arr = [1,2,3];
const name = 'tapas';
const merged = [...arr, ...name];
console.log(merged);
The output,
In such cases, use the concat()
method instead,
const arr = [1,2,3];
const name = 'tapas';
const merged = [].concat(arr, name);
console.log(merged);
The output,
4. Using the push()
array method
We use the push()
method to insert an element at the end of the array. We can use this method to merge two or more arrays as well. Please take a look,
const arr1 = [1,2,3];
const arr2 = [4,5,6];
// Merge arrays
const merged = arr1.push(...arr2);
console.log(merged); // 6
console.log(arr1); // [1,2,3,4,5,6]
console.log(arr2); // [4,5,6]
A few essential points to note here,
- The
push()
method inserts an element into an array. The method changes the array and returns the number of elements of the array after insertion. So, in the example above, the first array,arr1
, will be changed to accommodate the new elements. The return value is6
from thepush()
method is assigned to themerged
variable. We must spread the array while pushing its element to the other array,
arr1.push(...arr2)
. Missing the spread operator will insert the entire array to the other array,const arr1 = [1,2,3]; const arr2 = [4,5,6]; // Merging without the ... on arr2 const merged = arr1.push(arr2); console.log(merged); // 4 console.log(arr1); // [1,2,3,[4,5,6]] console.log(arr2); // [4,5,6]
So, how do we merge more than two arrays using the push()
method? Here it is,
const arr1 = [1,2,3];
const arr2 = [4,5,6];
const arr3 = [7,8,9];
// Merge more than two arrays
arr1.push(...[...arr2, ...arr3]); // [1,2,3,4,5,6,7,8,9]
5. Using the reduce()
array method
The last way to merge multiple arrays is using the reduce()
method.
This way of merging array is not recommended as it is closer to the
for-loop
approach we have seen above with the extra headache ofreduce
. We are discussing it here for the sake of building awareness!
With the reduce
method, we can initialize a variable(arr
) with the value of arr1
and then insert the elements of arr2
one by one to arr
.
const arr1 = [1,2,3];
const arr2 = [4,5,6];
const merged = arr2.reduce((arr, item) => {
arr.push(item);
return arr;
}, arr1);
console.log(merged);
The output,
In Summary
To Summarize,
- There are more than a couple of ways to merge two or more arrays into one in JavaScript.
- Using the
spread operator
or theconcat()
method is the most optimal solution. - If you are sure that all inputs to merge are arrays, use
spread operator
. In case you are unsure, use theconcat()
method. - You can use the
push()
method to merge arrays when you want to change one of the input arrays to merge. - Using the
reduce()
method to merge arrays is a bit of overhead.
Do you know any other ways to merge arrays in JavaScript? Please feel free to let us know in the comment section below.
You can find all the source code used in this article from my GitHub repo,
I hope you found the article insightful and informative. Please like/share so that it reaches others as well.
Let's connect. I share my learnings on JavaScript, Web Development, and Blogging on these platforms as well,