JavaScript: 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 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]
Spread Your Love By Sharing It On:
Write With ❤️ By Jorcus

Leave a Comment