How to Efficiently Merge Arrays in JavaScript

Chad Campbell
JavaScript in Plain English
7 min readFeb 17, 2022

--

Photo by Gabriel Heinzer on Unsplash

Recently, I needed to combine two Array objects in JavaScript. I wanted an easy-to-read approach that ran fast. This led me to comparing a variety of the Array functions available in JavaScript. I decided to create some performance benchmarks comparing several approaches. I was very surprised by what I saw. In this article, I’ll share what I learned. If you want a quick takeaway:

The Takeaway (or TL;DR)

The safest approach is to use the concat method of an Array object to merge two Arrays. If speed is critical, you may consider using JavaScript’s spread syntax and the Array object’s push method for smaller Arrays. You should test merging Arrays with the largest number of elements you expect to avoid unintended consequences though.

Follow me if you found this takeaway helpful. The repo used to arrive at the conclusion above can be found here. This repo also includes the samples used in this article to merge Arrays in JavaScript. This article will also include a performance analysis comparing the ways of combining Arrays.

Coding Ways to Combine Arrays in JavaScript

Personally, when I write code, I aim to write code that a) works b) is easy for the next person to read (i.e. maintain) and c) is performant at runtime. These three goals can collide at times. Still, a good starting point is to use standard, baked-in features when you can. For that reason, this section will not show a custom implementation.

In this section, I’ll show you how to merge Arrays with the concat method. Then, I’ll show you one way to combine Arrays with the push function. Finally, I’ll integrate the spread syntax with the push function as a final way of fusing Arrays together. These three implementations will serve as the foundation for the performance analysis shown in the next section. Let’s begin.

Merging Arrays with the Concat Method

The concat function is the de-facto standard for merging arrays in JavaScript. In fact, the MDN documentation specifically states this “method is used to merge two or more arrays”. Reading this, it would make sense to implement code like the following sample:

sample 1

Sample 1 appends the elements of array2 onto the end of array1. Notably, array1 and array2 are not changed by the concat function. Instead, a new Array is created. The following image shows the behavior of the concat function.

image 1

Image 1 reinforces the code from sample 1. Sample 1 shows concise, easy-to-read code. Since the concat function has been in JavaScript since ES1, it’s safe to assume it’s robust. This OG Array function seems like the correct path to go down. Still, I wondered what would happen if the push function was used instead.

Combining Arrays with the Push Function

The push function adds elements to the end of an existing Array. This behavior is slightly different than the concat function because an existing Array is changed. The following example shows array2 being pushed onto the end of array1.

image 2

The push function is used in image 2 to update array1 to include the contents of array2. While array1 is changed, array2 is not. If changing an existing Array is acceptable for you, the push function may meet your needs. The code reflecting image 2 is shown in the following sample.

sample 2

Like the concat function, the push function has been a function on the Array type since ES1. The code in sample 2 is still easy-to-read. Yet, it’s not as concise as the code in sample 1. To condense this code down to one single line, a more recent addition to the JavaScript language can be used. This addition is the spread syntax.

Fusing Arrays with the Spread Syntax

The spread syntax can be used to expand an Array into individual elements. These elements can then be treated as independent shallow copies of the original elements. Since the push function accepts one or more parameters, the spread syntax can be used in the push function like this:

sample 3

Sample 3 condenses sample 2 down to a single line of code. It’s a bit more terse. If the spread syntax is unfamiliar to you, this line is less readable than the previous two samples. Still, the following image may help you visualize the behavior.

image 3

Image 3 looks more complicated than the previous images. Knowing that there are two simpler and more readable options, one might wonder if the spread syntax is worth considering. I was curious at least. The results I saw when comparing the performance of merging Arrays in different ways surprised me.

Comparing the Performance of Merging Arrays

To compare the performance of merging Arrays, I created a tool to benchmark the performance. That tool can be found in this repository. If you clone the repository, you can run the tool for yourself. When running, you’ll see something that looks like this:

image 4

The tool shown in image 4 lets you a) setup two arrays b) specify the number of times to merge the arrays and c) specify the approaches to use when merging arrays. I used this tool to test three distinct scenarios:

  1. Arrays of primitive values
  2. Arrays of objects
  3. An array of primitive values with an array of objects (i.e. a hybrid)

For each of these scenarios I ran a test 100 times using Arrays with 1, 10, 100, 1,000, 10,000, 100,000, and 1,000,000 elements. The appropriate way to compare these would be to use Big-Ω (i.e. Big-O) notation. However, for simplicity I just ran tests on a 2020 13-inch MacBook Air running macOS Version 12.0.1 in Google Chrome 96.0.4664.55. You can run them for yourself to see if you get other results. If you want to learn about Big-O notation, checkout the following affiliated Big-O notation course on Educative. The following three images show the results I personally observed.

image 5: results merging arrays of primitive values
image 6: results merging arrays of objects
image 7: results of a hybrid scenario

Images 5–7 show the results I observed. The green cells show the fastest approach used for a test scenario. The orange cells show the slowest approach used for a test scenario. At first glance, the spread syntax looks like it’s usually the fastest approach when considering all three scenarios together. That is, until you get to larger Arrays. In fact, as indicated by the “N/A”, the spread syntax won’t even work with larger Arrays! 😲

The spread syntax fails to work with larger Arrays. When testing with 100,000 elements, the spread syntax generated a RangeError with the message: Maximum call stack size exceeded. I manually adjusted the number in the tool to identify the actual number of elements that caused this error. I found that number of elements to be 63,653. It’s unclear to me at this time why this number of elements causes this error. I don’t know if it’s my specific environment, specific code, or something else. I believe it’s beyond the scope of this article though.

Since the spread syntax is baked-in to JavaScript, I did not expect to run into a RangeError. The reason this happens is because the spread syntax loads the entire source array (i.e. array2) onto the stack. This means that larger Arrays may cause an Error like this RangeError. I say may because, the actual consequence is up to the browser engine in use (source).

If you need to merge smaller Arrays the spread syntax can help you do this efficiently. For larger Arrays, with more elements, use the concat function. Regardless of your scenario, test your code with the most number of elements you expect. The goal is to create code that works, is efficient, and easy-to-read.

In this article, you saw three ways to merge two Arrays in JavaScript. If you find a more efficient approach, I hope you’ll share it in the comments below. If you found this article helpful, please applaud 👏, or clap, below. This will let me, and others, know you found it useful. If you would like to learn of similar content, I encourage you to follow me now. Thanks for reading.

More content at plainenglish.io. Sign up for our free weekly newsletter. Get exclusive access to writing opportunities and advice in our community Discord.

--

--

Writing for Ecofic Learning, LLC. Five-time Microsoft MVP. Independent Software Engineer. Internationally published book and article author. @chadcampbell