fbpx

Four important ways to Merge Array in Javascript

Many times we need to merge two arrays to perform some tasks. JavaScript provides various ways to perform this task.

#1. concat()

This method merge two array but does not affect original array. It returns new merge array.

var arr1 = [1,2,3];
var arr2 = [4,5,6];
var merge_array = arr1.concat(arr2)
console.log(merge_array) // [1,2,3,4,5,6]

#2. With spread operator

spread operator () allows us the privilege to obtain a list of parameters from an array. We can use this feature to merge two or more than two array.

var arr1 = [1,2,3];
var arr2 = [4,5,6];
var arr3 = [7,8,9];
var merge_array = [...arr1,...arr2,...arr3]
console.log(merge_array) // [1,2,3,4,5,6,7,8,9]

#3. push

Array provides us a push method to insert one or more than one value in an array. So with the help of the spread operator and push method we can merge two or more than two arrays. It affects the original array on which we are performing push operation.

var arr1 = [1,2,3];
var arr2 = [4,5,6];
var arr3 = [7,8,9];
arr1.push(…arr2,…arr3)
console.log(arr1) // [1,2,3,4,5,6,7,8,9]

#4. using push & apply

One other way to merge two arrays is by using the apply method on array push. It is similar to concat but it modifies on the original array. It is faster than concat()

var arr1 = [1,2,3];
var arr2 = [4,5,6];
arr1.push.apply(arr1,arr2)
console.log(arr1) // [1,2,3,4,5,6]

Checkout Important method of JavaScript array