We are going to create a function called mergeArrays that will accept two arrays, arr1 and arr2, as arguments.

The goal of the function is to merge the two arrays and return a new array containing the merged arrays. We are going to look at two ways of merging two arrays together. One way will use the for...of loop and the other will use the JavaScript method concat().

Example:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
mergeArrays(arr1, arr2);

//output: [1, 2, 3, 4, 5, 6];

For…of Loop Example

Since we need to return a new array after merging arr1 and arr2, we are going to create a new variable called arr3 and assign it an empty array.

let arr3 = [];

Next, we are going to use the for...of loop to iterate through arr1 and push all the elements from that array into the arr3 array.

for(el of arr1){
   arr3.push(el);
}

We do the same thing with the arr2 array.

for(el of arr2){
   arr3.push(el);
}

Now that both arrays are merged and in arr3, we can return it.

return arr3;

That’s it. Here is the full code:

function mergeArrays(arr1, arr2){
  let arr3 = [];

  for(el of arr1){
   arr3.push(el);
  }
  for(el of arr2){
   arr3.push(el);
  }

  return arr3;
}

#algorithms #coding #javascript

JavaScript Algorithm: Merge Two Arrays
1.40 GEEK