Merge two Arrays in Javascript (3 ways)

While working in javascript arrays, we often need to merge two arrays. This article will see different ways to merge two arrays using different methods and various example illustrations.

Table of Contents:

Merge two arrays using concat()

Javascript’s concat() method merges two or more arrays and returns the new array.

Example:-

Merge the below arrays.

  • myArray1 = [5, 7, 9]
  • myArray2 = [8, 5, 10]

Code:-

var myArray1 = [5, 7, 9];
var myArray2 = [8, 5, 10];
var myFinalArray = myArray1.concat(myArray2);
console.log(myFinalArray);

Output:-

[ 5, 7, 9, 8, 5, 10 ]

Explanation:-

  • In the above code, we are merging two arrays myArray1 and myArray2 using the concat() method.

Merge two arrays using Spread operator

Javascript’s Spread syntax(…) allows any iterable like an array to be expanded at places where zero or more arguments are requiredOne can also use it to expand object expressions where zero or more key-value pairs are needed.

Example:-

Merge the below arrays.

  • myArray1 = [5, 7, 9]
  • myArray2 = [8, 5, 10]

Code:-

var myArray1 = [5, 7, 9];
var myArray2 = [8, 5, 10];
var myFinalArray = [...myArray1, ...myArray2];
console.log(myFinalArray);

Output:-

[ 5, 7, 9, 8, 5, 10 ]

Explanation:-

  • Here, in the above code, we add two arrays to a final array using the Spread syntax(…).

Merge one array to another using push()

Javascript’s push() method adds one or more elements to the end of the calling array. The length of the new array is returned by the push() method.

Example:-

Merge the below arrays.

  • myArray1 = [5, 7, 9]
  • myArray2 = [8, 5, 10]

Code:-

var myArray1 = [5, 7, 9];
var myArray2 = [8, 5, 10];
function mergeTwoArrays(_arrayA,_arrayB)
{
  if(!_arrayB.push || !_arrayB.length)
 // if _arrayB is not an array, or empty, then return _arrayA
   return _arrayA;    
 // if _arrayA is empty, return _arrayB
  if(!_arrayA.length) 
   return _arrayB.concat();     
  // iterate through all the elements of _arrayB
  for(var i = 0; i < _arrayB.length; i++)
  {
      // add elements of _arrayB to _arrayA
      _arrayA.push(_arrayB[i]);
  }
  return _arrayA;
}
console.log(mergeTwoArrays(myArray1, myArray2));

Output:-

[ 5, 7, 9, 8, 5, 10 ]

Explanation:-

  • Herein the above function, if _arrayA is empty or not an array, the function returns _arrayB.
  • If _arrayB is empty or not an array, then the function returns _arrayA.
  • If both the above statements are falseiterate _arrayB till its length and add all its elements to _arrayA using push().

Read More:

I hope this article helped you merge two arrays in javascript. Good Luck !!!

Advertisements

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top