How to Merge Two or More Arrays in JavaScript
Table of Contents
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:
JAVASCRIPTconst array1 = [1, 2, 3];
const array2 = [4, 5, 6];
Now let's use the concat
function to merge the two arrays:
JAVASCRIPTconst 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:
JAVASCRIPTconst 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!
- Getting Started with Svelte
- Getting Started with Express
- Git Tutorial: Learn how to use Version Control
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Getting Started with React
- Setting Up Stylus CSS Preprocessor