How To Merge Two Arrays in JavaScript

How To Merge Two Arrays in JavaScript

Use the .concat() method or the spread operator

Image for postPhoto by Clayton Cardinalli on Unsplash

Merging two arrays, whether the arrays already exist or the second array is yet to be defined, is a common task. Moreover, if you?re not careful then the merge may not function as you?d expect.

Let?s take a look at two arrays [1,2,3] and [4,5,6] that we want to merge to become [1,2,3,4,5,6]. Your first instinct might be to use the + sign or .push() method, but neither of these yield the proper result.

a = [1,2,3]b = [4,5,6]console.log(a + b); // [1,2,34,5,6]console.log(a.push(b)); // [1,2,3,[4,5,6]

In the first example, the concatenation operator + is treating each item as a string. As a result, the last item in a and first item in b are concatenated producing 34.

In the second example, b is treated as a single value and added to the end of a producing a nested array.

To produce the array that we?re looking for, we need to use either the .concat() method or the spread … operator.

The .concat() Method

This has long been the de-facto technique for concatenating arrays. The method is invoked from the parent array ? the one that will be first in order ? and accepts any number of arrays thereafter.

let a = [1,2,3];let b = [4,5,6];let c = a.concat(b);console.log(c); // [1,2,3,4,5,6]

The Spread Operator

Supported in ES6+, the spread operator … will ?unpack? the items when used with an array. The visual I use creates a single sequence of dominoes by unpacking multiple boxes.

let a = [1,2,3];let b = [4,5,6];let c = […a, …b];console.log(c);

Which Should I Use?

This is an interesting question. Some differentiate based on the status of the arrays. Others have noted that there may be differences when chaining multiple methods together.

I like to remember as little as possible so I have adopted a stance of using spread by default, using .concat() only when necessary. Spread is more flexible, especially when it comes to making changes.

Given the example we?ve used in this tutorial, what happens if we now need to add [0,0,0] to the front of our sequence? The modification to the code with spread is much easier.

let a = [1,2,3];let b = [4,5,6];let c = [0,0,0].concat(a,b);let d = [0,0,0,…a,…b];

With .concat(), we wrapped the previous statement with an array literal and either pass two arguments to the method or chain them one after another.

With the spread operator, the change is minimal, adding the elements before unpacking a and b.


No Responses

Write a response