How to Merge Arrays Together in Javascript

How to Merge Arrays Together in Javascript

Ferenc Almasi • 🔄 2020 November 01 • 📖 2 min read

There are a number of ways to merge arrays together in JavaScript. You can either use Array.concat:

// Using Array.concat
const array1 = ['📗', '📘'];
const array2 = ['📕', '📙'];

array1.concat(array2);
merge.js
Copied to clipboard!

You can also merge more than two arrays into one using concat in the following way:

// Using Array.concat
const first  = ['1️⃣', '2️⃣'];
const second = ['3️⃣', '4️⃣'];
const third  = ['5️⃣', '6️⃣'];

// This will result in ['1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣']
[].concat(first, second, third);
merge.js
Copied to clipboard!

Keep in mind that both solution will return a new array instead of modifying the existing ones. Another way to combine arrays together, is by using destructuring:

// Using the destructuring assignment
const array1 = ['📗', '📘'];
const array2 = ['📕', '📙'];

[...array1, ...array2];
merge.js
Copied to clipboard!

Again, this will create a new array instead of modifying the originals. You can also create a simple function to combine as many arrays as you would like:

function combine() {
    const array = [];

    [...arguments].forEach(arg => {
        array.push(...arg);
    });

    return array;
}

combine([1]);           // returns [1]
combine([1], [2]);      // returns [1, 2]
combine([1], [2], [3]); // returns [1, 2, 3]
merge.js
Copied to clipboard!

This works by making use of the arguments object, that is accessible inside functions.

How to Merge Arrays Together in Javascript
If you would like to see more Webtips, follow @flowforfrank
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

Resources:

JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in less time.

Learn More

Recommended