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 TypeScript
Create an RSS Reader in Node
How to deploy a PHP app using Docker
How to deploy a MySQL Server using Docker
How to deploy an Express app using Docker
How to deploy a Node app using Docker
Using Puppeteer and Jest for End-to-End Testing
How to Scrape the Web using Node.js and Puppeteer
Learn how to build a Slack Bot using Node.js
Creating a Twitter bot with Node.js
Using Push.js to Display Web Browser Notifications
Setting Up Stylus CSS Preprocessor
