How to merge two arrays in JavaScript

published: 30 Sep 2022

2 min read

How to merge two arrays in JavaScript

In vanilla JavaScript, there are multiple ways to combine all elements of two arrays and returns a new array. You can either use the Array.concat() method or the spread operator (...) to merge multiple arrays.

The Array.concat() takes in one or more arrays as input and merges all subsequent arrays into the first:

const fruits = ['Apple', 'Orange', 'Banana'];

const moreFruits = ['Kiwi', 'Lemon'];

// merge all fruits
const allFruits = fruits.concat(moreFruits);

console.log(allFruits);

// ['Apple', 'Orange', 'Banana', 'Kiwi', 'Lemon']

This method works in all modern browsers, and IE6 and above. You can also merge more than two arrays by using the Array.concat() method:

const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [5, 6];

let combined = [].concat(arr1, arr2, arr3);

console.log(combined); // [ 1, 2, 3, 4, 5, 6 ]

Notice the [].concat() syntax we used in the above example to merge arrays. It is similar to the first example except that the input arrays are merged with an empty array.

If you only care about modern browsers, better to use the ES6 spread operator to merge the arrays:

const fruits = ['Apple', 'Orange', 'Banana'];

const moreFruits = ['Kiwi', 'Lemon'];

// merge all fruits
const allFruits = [...fruits, ...moreFruits];

console.log(allFruits);

// ['Apple', 'Orange', 'Banana', 'Kiwi', 'Lemon']

What if the arrays contain duplicate elements? There is no 'built-in' way to remove duplicates in ECMAScript 5. However, you can use the ES6 Set object along with spread operator to filter out all duplicates:

const fruits = ['Apple', 'Lemon', 'Banana'];

const moreFruits = ['Kiwi', 'Lemon'];

// merge all fruits
const allFruits = [...new Set([...fruits, ...moreFruits])];

console.log(allFruits);

// ['Apple', 'Lemon', 'Banana', 'Kiwi']

This approach only works in modern browsers and Node.js. Take a look at this article to learn more about removing duplicates from an array in JavaScript.

To learn more about JavaScript arrays, check out this guide that explains in detail how JavaScript arrays work and how to use them to store multiple pieces of information in a single variable.

How to merge two arrays in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, nodejs, programming
Check out what's on in the tag: javascript, nodejs, programming, array