JavaScript Merge Arrays – How to merge two or more arrays in JavaScript

4 weeks ago Lalit Bhagtani 0

JavaScript Merge Arrays

In this tutorial, we will learn about how to merge two or more arrays in JavaScript.

JavaScript Merge Arrays

Array Concat Method :-

JavaScript Array objects contains a concat method, which can be used to join two or more arrays. This method takes variable number of array objects. It returns a new array by combining all the array objects passed as an argument with an array object on which concat method has been invoked.

Syntax :-

Array.concat(array...)

Let’s see the example :- 

<script>
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];

var merge1 = arr1.concat(arr2);
console.log(merge1);

var arr3 = [7, 8, 9];

var merge2 = arr1.concat(arr2, arr3);
console.log(merge2);
</script>

jQuery Merge Method :-

The jQuery merge method is used to append the elements of second array into the first array. The order of elements in the arrays are preserved, with elements from the second array are appended at the end of first array.

Syntax :-

$.merge(firstArray, secondArray);

Let’s see the example :- 

<script>
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];

var merge = $.merge(arr1, arr2);
console.log(merge);
</script>

References :- 

  1. Array Concat Docs
  2. JQuery Merge Docs

That’s all for how to merge two or more arrays in JavaScript. If you liked it, please share your thoughts in comments section and share it with others too.