merge two arrays in javascript
Code snippet for how to how to merge two arrays in javascript with sample and detail explanation
Merging arrays is a very common operation in programming, and especially so in JavaScript, given its flexibility in handling arrays. In this article, we’ll look at how to combine two arrays in JavaScript using various methods.
Code snippet: Using the concat() method
The first method we’ll discuss is the “concat()” method, which is built-in to the JavaScript Array object. Using “concat()”, we can easily combine two or more arrays.
let array1 = ['Hello', 'Great'];
let array2 = ['World', 'People'];
let mergedArray = array1.concat(array2);
console.log(mergedArray);
// Output: ["Hello", "Great", "World", "People"]
Code Explanation for Using the concat() method
In the above example, we have two arrays: ‘array1’ and ‘array2’. To merge these arrays, we call the “concat()” method on the ‘array1’ object and pass ‘array2’ as an argument. The “concat()” method returns a new array that includes the elements from both ‘array1’ and ‘array2’. Our new merged array ‘mergedArray’ thus contains all the elements of ‘array1’ and ‘array2’.
Code snippet: Using the spread operator
Another way of merging two arrays is by using the ES6 spread operator ”…” .
let array1 = ['Hello', 'Great'];
let array2 = ['World', 'People'];
let mergedArray = [...array1, ...array2];
console.log(mergedArray);
// Output: ["Hello", "Great", "World", "People"]
Code Explanation for Using the spread operator
In this example, we see the use of the ES6 spread operator ”…“. This operator takes each element from the array and spreads it out. When we put “…array1” and “…array2” inside brackets [], we’re effectively creating a new array (mergedArray) with all the items from ‘array1’ and ‘array2’.
Note that both these methods do not alter the original arrays—they simply return a new array that combines the elements of the input arrays. This is beneficial because it maintains the immutability of the data—an important principle in functional programming.