Merge Array in JavaScript

Overview
Arrays are a simple data structure to store elements in an orderly manner that can be accessed via indexes. In this article, we'll see how two or more arrays can be merged together using various different operators and methods and understand them using code examples.
Introduction
The array is a common data structure that stores elements as an ordered collection of indexed items. We may need to merge two or more arrays in case data is coming from various different streams and we want to merge them, so we have the whole data in a single data structure.
Consider these two arrays: [ 1, 2 ] and [ 3, 4 ]. After merging both, we should have the array: [ 1, 2, 3, 4 ].
There are a lot of ways merging arrays can be done. All the methods can be categorized based on:
- Based on duplicate items:
- Merging keeping the duplicate items.
- Merging without keeping the duplicates.
- Based on Immutability:
- Immutable - A new array is created after merging.
- Mutable - The same array is modified to contain the merged array.
While discussing all the methods to merge arrays in JavaScript, we'll discuss both these categories and tell which type it is in each category.
Ways to Merge Arrays Using JavaScript
Merge without removing duplicate elements
We can merge two or more arrays without removing duplicate items and directly adding all the arrays' elements to the final merged array. Consider three arrays:
This example had three arrays. This can be extended to have an infinite number of arrays. Now let us see how we can merge these arrays without removing duplicates first.
Using the traditional for loop
Define all the three arrays that we want to merge:
Construct a function that merges two arrays given as input. Using a simple for loop, we can loop through the second array and keep pushing its elements into the first array. This will give us the final merged array into the first array.
Now, to merge two arrays, we can simply call the function and pass two arrays into it, like this:
Output:
To merge three arrays, we can get the final merged array following two steps.
- Merge the first two arrays, and store the merged array.
- Merge the output of previously merged array with the third array to get the final merged array.
Code: A single line of code for the same:
Output:
This can be extended to merge an infinite number of arrays. But we'll have to call the function a lot of time, which will make the final calling code hard to understand.
To make this easier even further, we can create function that takes up any number of arrays, and then loops to merge them all one by one.
Properties of this method:
- Mutable: This method mutates the original array and returns the merged array by modifying one of the original arrays. No new arrays is formed.
- Duplicates are not removed: This method does not check for duplicates. It simply loops through the array and pushes elements to the merged array.
Using the Spread operator
Spread operator ( ... three simultaneous dots) is used to spread the elements of the array like this:
It returns the elements of the array. This can be used to merge two or more arrays. We can spread the elements of multiple arrays and then store them all inside another array.
This is how we can spread the elements of the array and store them inside another array:
To merge two arrays, we can store two spread arrays like this:
This can be extended to three or even any number of arrays. You just need to spread the array and store them inside a new array.
// Merging three arrays
const merged = [ ...arr2, ...arr2, ...arr3 ]
Properties:
- Merging using the spread operator is immutable. The original array is not modified. A new merged array is formed and returned.
- Does not remove duplicates: It does not remove duplicates while merging arrays. It simply adds all the elements to the newly created array.
Using the concat() array method
concat() method takes in arrays as its argument and simply returns the merged array.
Output:
Properties:
- Merging using concat() is immutable. The original array is not modified. A new merged array is formed and returned.
- Does not remove duplicates: It does not remove duplicates while merging arrays.
Using the push() array method
push() method can also be used to merge arrays together. push() method is actually used to push elements to the back of another array. Consider this example:
You can also spread the elements of another array and push it to the first array. This is how merging can be performed.
This can be extended to merge three arrays as well.
This can be extended to merge any number of arrays.
Properties:
- This is a Mutable way of merging because it modifies the original array to store the final merged array by pushing elements. We can also push all the elements into an empty array, but it still remains mutable because we are anyways modifying an original array.
- Does not remove duplicates: This method does not check for duplicates and directly pushes elements to the back of an array.
Using the reduce() array method
Before understanding how reduce() can be used to merge arrays in JavaScript, let us understand how this method works.
reduce() method takes in two parameters:
- Reducer callback function
- Initial value of the accumulator
The reduce() function maps through the entire array and runs the reducer callback function on each array element. It calculates on the previous value and returns the new value (according to the reducer function).
What is an accumulator? An accumulator accumulates data inside it. In every iteration, the value of the accumulator is modified in a way to form a new value after including data from the current iteration.
Let us see an example to understand: Use of reducer() function to add all the numbers of the array:
Output:
Explanation:
- We call the reduce function passing the reducer function and the initial value as a parameter
- Reduce() method will run a loop, and while mapping through each element of the array, it will add the previously accumulated value and the current value of the array.
- To start with, the value of the accumulator is zero.
- In each loop, the reducer function adds to the accumulated value to get the final sum of all the array elements.
Now, to merge two arrays using the reducer function, we'll pass the first array as the initial value, map through the second array, and keep accumulating the values from the second array inside the first array to get the final merged array.
Look at this code:
Output:
Explanation:
- The initial value of the accumulator is passed as the first array.
- reduce() maps through the second array and pushes the element from arr2 into the previously accumulated value in each loop.
- Finally, all the elements of arr2 are pushed to the end of arr1, and we get the merged array.
Properties:
- Immutable: This method is not mutating the original array. This method is taking the first array as the starting value of the accumulator in the reducer function but is not mutating the original array. A copy of the original array is made to the accumulator.
- Doesn't remove duplicates: This method straight-away pushes the elements of the second array into the accumulator and does not check for duplicates. Although, we can change the code to make it otherwise.
This way of merging arrays using reduce() will remove duplicates:
Output:
This method checks if the current element is not already present inside the accumulator, then push otherwise, simply return the accumulator value.
Using set() method
TheSet() object return the unique elements of the array. Let us see how this is used:
Set() can be used to remove duplicates from the merged array. Simply merge all the arrays, and then create a set of the merged array to get the set of unique elements of the merged array.
- Merge arrays normally, using spread operator
- Create a Set object. It will return the unique elements only.
Output:
Properties:
- Immutable: No original array is mutated. A new array named merged is created and returned.
- No duplicates: Duplicates are removed using the new Set() object. Hence, no duplicates are present in the merged array.
Using filter() Method
This method is used to merge arrays in JavaScript such that they do not contain duplicate values. The following steps are followed to merge arrays without keeping duplicates:
- Merge arrays normally, using the spread operator
- Filter the merged array such that there is only one occurrence of each element, i.e., no duplicates.
Output:
Explanation:
Step 1: In the first step, the arrays are merged together using the spread operator. Merging in this step can be done by any other method (discussed above) as well. The merged array produced using this step will contain all the elements of all the arrays, including the duplicates. Duplicates are removed in the next step. Step 2: In this step, duplicates are removed using the filter() method. The merged arrays are looped, and any element that repeats itself is filtered out. This way, a new merged array is formed, which does not contain duplicate elements.
Properties:
- Immutable: This method does not mutate any of the original arrays, but creates a new array named merged and stores the merged elements.
- Removes Duplicates: This method is mainly used for removing duplicates from the merged array using the filter() method.
Which is better: The spread operator or the concat() method?
Both spread operator and concat() methods merge two or more arrays. Despite being almost the same, they have a few differences. Before discussing their differences, let us understand both these methods in detail with examples:
- Array.prototype.concat(): The concat() method is used to merge two or more arrays. This method creates a new array and returns the merged array. For example:
Output:
- Spread operator(...): The Spread operator is used to spread out the elements of the array. This property can be used to create new arrays or merge the original ones by spreading out their elements and then merging them together. Look at the example below to understand:
Output:
Now, let us discuss their differences:
- Case of Strings: In the case of strings, the spread operator spreads the entire string into its characters. If we want to merge an array with a string, concat() performs as expected, but the spread operator gives the following result.
Output:
While merging using the Spread operator, it might give unexpected results if anything other than an array gets spread out. While the concat() method simply pushes anything to the first array.
- Size of the arrays: The spread operator iterates through all the arrays, spread out their elements, and then merging happens inside a new array. In the case of big-sized arrays, this might give an error of Maximum call stack size exceeded. On the other hand, the concat() method is faster and more efficient in merging large-sized arrays.
Note: For smaller arrays, the spread operator is 50% faster than the concat() method. While in the case of large-sized arrays, the concat() method is multiple times faster than the spread operator.
- Mutation: The Spread operator always creates a new merged array and returns that array. It does not mutate any of the original arrays. Hence, the spread operator is the immutable method. On the other hand, the concat() method mutates the array on which this method is applied. Hence, the concat() method is a mutable method.
So, which one is better? The answer to this question depends on the size of the array and the data structures being merged. But to conclude, the spread operator is better in the case of small size arrays, and the concat() method is faster and more efficient in case the array size of large.
Conclusion
- Merging two or more arrays can be done by mutating the original arrays or otherwise.
- Some methods simply append elements to form the merged array and do not remove duplicates, while others do not accept duplicates.
- Some methods which do not remove duplicates are traditional loop, spread operator - '...', concat(), push(), etc.
- Merging while removing duplicates can be done using:
- filter() method: filter out the repeating elements and the merged array gets rid of any duplicates.
- Set method: create a Set of the merged array, and all the duplicates get removed.
- reduce() function: reduce the merged array while keeping the unique elements.
- The spread operator works very well for small-sized arrays, but the concat() method is faster and more efficient for larger arrays.