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:

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access exclusive interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Remove ads to learn without distractions
Become a Pro

Recommended