Join Digital Nomads and Remote Workers to Ask Questions, Share Experiences, Find Remote Jobs and Seek Recommendations.

JavaScript: How to Merge Two Arrays

,

There are a couple ways to merge two arrays in JavaScript. In this blog, I would like you to share with 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 doesn’t change the existing array. But it creates 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 to 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]

We Work From Anywhere

Find Remote Jobs, Ask Questions, Connect With Digital Nomads, and Live Your Best Location-Independent Life.