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 Solid
Managing PHP Dependencies with Composer
Getting Started with Svelte
Getting Started with Electron
How to Set Up Cron Jobs in Linux
How to deploy a PHP app using Docker
How to deploy an Express app using Docker
Getting Started with Sass
Using Puppeteer and Jest for End-to-End Testing
Getting Started with Handlebars.js
Getting User Location using JavaScript's Geolocation API
Building a Real-Time Note-Taking App with Vue and Firebase
