JavaScript: How to Merge Two Arrays

How To Merge Two Arrays
Last Updated on

There are a couple ways to merge two arrays in JavaScript. In this blog, I would like you to share you the methods to merge two arrays in JavaScript.

Array.concat()

The first method is the most common method we use in the past. This method don’t make any change to the existing array. But it create a new array for the new variable.

const arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
const combined = arr1.concat(arr2); // [0, 1, 2, 3, 4, 5]

Array.push.apply()

The second way merge two arrays is to use array.push.apply() push the arr2 into the arr1.

const arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
const combined = [].push.apply(arr1, arr2); // 6
console.log(arr1); // [0, 1, 2, 3, 4, 5]

Spread Syntax

Spread syntax is the most concise and easiest method to merge the arrays. In most case, I would recommend using this method to merge the array because it’s clean enough.

// RECOMMEND
const arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
const combined = [...arr1, ...arr2] // [0, 1, 2, 3, 4, 5]

Array.push() + Spread Syntax

This method is very similar to the Array.push.apply() method. It will also will push arr2array to the arr1, to print out the merged array just print arr1. But in this case, we use spread syntax to push the array. Otherwise, it will be a nested array. You can experiment it without the spread syntax.

const arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
const combined = arr1.push(...arr2); // 6
console.log(arr1); // [0, 1, 2, 3, 4, 5]