How to Merge Two or More Arrays in JavaScript

Updated onbyAlan Morel
How to Merge Two or More Arrays in JavaScript

When you are working with multiple arrays, sometimes you'll want to merge them in a single array.

You could iterate through one of them and add each value to the end of the other array, but thats inefficient and modifies one of the arrays.

In this post, we'll look at two ways to merge arrays without modifying either one in JavaScript.

Using concat

One way to merge arrays is to use the concat function.

This function is built-in for arrays and will return a new array containing the values of the original array and the secondary array that you pass in as the parameter.

Let's start with our two arrays:

JAVASCRIPT
const array1 = [1, 2, 3]; const array2 = [4, 5, 6];

Now let's use the concat function to merge the two arrays:

JAVASCRIPT
const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const mergedArray = array1.concat(array2); console.log(mergedArray);
BASH
[1, 2, 3, 4, 5, 6]

Using the Spread Operator

A more modern way to merge arrays is to use the spread operator.

This operator takes an array and spreads it out into a list of individual values.

We can use this when defining a new array and spread both arrays out into it, filling it with the values from both arrays.

Let's see this in action:

JAVASCRIPT
const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const mergedArray = [...array1, ...array2]; console.log(mergedArray);
BASH
[1, 2, 3, 4, 5, 6]

Conclusion

In this post, we looked at the two best ways to merge arrays while keeping the original arrays intact.

Simply use the concat function or the spread operator to merge arrays.

Thanks for reading and happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.