Many times while working on any project we need to merge the array and we want sometimes an efficient way to merge and sometimes we want a quick and dirty way to merge the array. In this blog post, we will explain a different way to merge the array some are the in-place merging and some give a new merged array
#1. Using Array.Concat
JavaScript Array objects have a method called concat
that allows you to take an array, combine it with another array, and return a new array.
let arr1 = [1,2,3]
let arr2 = [4,5,6]
arr1.concat(arr2)
conole.log(arr1) // [1, 2, 3, 4, 5, 6]
In this arr1 array merge with arr2 . Using this way arr1 is updated array in which arr2 merged.
#2. Using spread operator (…)
You can also accomplish the same thing using spread syntax. Spread syntax became standard in ES6 and allows us to expand an iterable to be used as arguments where zero or more arguments (or elements) are expected. This is applicable when creating a new array literal.
let arr1 = [1,2,3]
let arr2 = [4,5,6]
conole.log([...arr1, ...arr2]) // [1, 2, 3, 4, 5, 6]
Also Read: Rest Parameter and Spread syntax and their use-case
#3. Using for loop
let arr1 = [1,2,3];
let arr2 = [4,5,6];
for(let i = 0; i < arr2.length; i++ ) {
arr1.push(arr2[i]);
}
console.log(arr1) // [1,2,3,4,5,6]