How to Merge Two Arrays in JavaScript

Tyler Tyler (270)
Total time: 1 minute 

Learn how to merge two arrays together in JavaScript.

Posted in these interests:

27 guides
65 guides

Some languages allow you to concatenate arrays using the addition operator, but JavaScript Array objects actually have a method called concat that allows you to take an array, combine it with another array, and return a new array.

let arr1 = [0, 1, 2];
let arr2 = [3, 5, 7];
let primes = arr1.concat(arr2);

// > [0, 1, 2, 3, 5, 7]

As you can see this creates a new array that is the combination of arr1 and arr2. Again, this does not affect either of the original arrays.

You can also accomplish the same thing using spread syntax. Spread syntax became standard in ES6 and allows us to expand an iterable to be used as arguments where zero or more arguments (or elements) are expected. This is applicable when creating a new array literal.

let arr1 = [0, 1, 2];
let arr2 = [3, 5, 7];
let primes = [...arr1, ...arr2];

// > [0, 1, 2, 3, 5, 7]

Just like Array.concat, this leaves the original arrays in tact, and concatenate their values to form a new array.