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!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- Getting Started with Handlebars.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor
- Getting Started with Vuex: Managing State in Vue