/**
                     * sort Used to order an array of integers in ascending order (O(n)).
                     * @param {Array} arr
                     * @return {Promise}
                     */
                    
                    function sort (arr) {
                        return new Promise(resolve => {
                            const sorted = [];
                            
                            for (const item of arr) {
                                setTimeout(item => sorted.push(item), item, item);
                            }
                            
                            setTimeout(() => resolve(sorted), arr.reduce((a, b) => a + b, 0) + 1);
                        });
                    }
                
                
                    «Nullam elementum blandit molestie.
                    Aenean condimentum lectus ut felis.
                    Phasellus fringilla nisl tincidunt dolor.»
                    
                    «Nam quis ante sed neque rhoncus.
                    Proin porta, turpis quis iaculis.
                    Maecenas tristique vulputate magna, vel laoreet.»
                    
                    «Nullam lobortis turpis a tempor molestie.
                    Maecenas fringilla nisl at malesuada porta.»
                
            
07/22/2019, Vasile Pește

How to merge two arrays in JavaScript

Merging two arrays is very common while programming and many algorithms have been written to solve this problem, most modern languages offer APIs to solve these types of recurring problems and JavaScript is one of these. With JavaScript 6 we have an elegant solution with a dedicated syntax and before JavaScript 6 we have a dedicated method, let’s see how to merge two arrays in JavaScript using the spread syntax and the concat method, concluding with a performance test to see which one is faster.

How to merge two arrays in JavaScript 6

There is a dedicated syntax for doing this: the spread syntax used in the following code which is pretty intuitive.

const array1 = [ 1, 2, 3 ];
const array2 = [ 4, 5, 6 ];

// Merge the previous two arrays.
const array3 = [ ...array1, ...array2 ];

That’s all! To be precise, this syntax was not created specifically to solve this problem, but it can be used to do so (and is widely used). Before JavaScript 6 we had to use concat, a method provided to array instances.

How to merge two arrays in JavaScript 5

The following is the equivalent JavaScript 5 code that can be used to merge two arrays.

var array1 = [ 1, 2, 3 ];
var array2 = [ 4, 5, 6 ];

// Merge the previous two arrays.
var array3 = array1.concat(array2);

As you can see there is a dedicated method for this task. Nowadays I recommend using the spread syntax since it’s more elegant, but it’s a personal choice, unless you have to support older browsers.

Performance test on spread syntax and concat

Are you wondering which is faster? After a testing phase on the latest browsers the spread syntax resulted slower than the concat method on all browsers, at least with large amount of data. Below the test and the results.

const array1 = [];
const array2 = [];
const mergeCount = 50;
let spreadTime = 0;
let concatTime = 0;

// Used to populate the arrays to merge with 10.000.000 elements.
for (let i = 0; i < 10000000; ++i) {
    array1.push(i);
    array2.push(i);
}

// The spread syntax performance test.
for (let i = 0; i < mergeCount; ++i) {
    const startTime = performance.now();
    const array3 = [ ...array1, ...array2 ];

    spreadTime += performance.now() - startTime;
}

// The concat performance test.
for (let i = 0; i < mergeCount; ++i) {
    const startTime = performance.now();
    const array3 = array1.concat(array2);

    concatTime += performance.now() - startTime;
}

console.log(spreadTime / mergeCount);
console.log(concatTime / mergeCount);
/*
 * Performance tests results.
 * Browser           Spread syntax      concat method
 * --------------------------------------------------
 * Chrome 75         626.43ms           235.13ms
 * Firefox 68        928.40ms           821.30ms
 * Safari 12         165.44ms           152.04ms
 * Edge 18           1784.72ms          703.41ms
 * Opera 62          590.10ms           213.45ms
 * --------------------------------------------------
*/

The test consists of adding 10 million elements to the arrays to be merged and then merging them 50 times using the spread syntax and the concat method, the execution time of each merge process is calculated and then the average execution time is calculated for both the solutions. As you can see the spread syntax can be much slower. I would like to add that if you are dealing with small amount of data probably you don’t have to worry about performance.

Conclusion

We have seen how to merge two arrays in JavaScript 6 and 5, both solutions are standard on all browsers but if you need to support older ones you must use the concat method. To conclude, if you are merging arrays with large amount of data, take in mind that the spread syntax is slower than the concat method.