Merging Arrays in JavaScript: A Comprehensive Guide


Greetings, developers! Merging arrays can be a common task in JavaScript—specifically, appending one array to another. We’ll merge all the ways of array concatenation in this post 😉.

Before we dive into the methods of appending arrays, lets understand what is concatenation. Concatenation involves combining two or more arrays to create a new array.And in JavaScript, we have so many tools to achieve this.


Using Spread Syntax

Beginning with spread syntax (…), this syntax creates a shallow copy of an array and doesn’t alter the originals:

JavaScript
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const combinedArray = [...arr1, ...arr2];
// Output: [1, 2, 3, 4, 5, 6]

console.log(arr1); // [1, 2, 3] (unchanged)
console.log(arr2); // [4, 5, 6] (unchanged)

Using Array.concat()

JavaScript
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const combinedArray = arr1.concat(arr2);
// Output: [1, 2, 3, 4, 5, 6]

The concat() method is a classic choice for array concatenation. It creates a new array by combining the elements of existing arrays:

Using Array.push()

While commonly used to add elements to the end of an array, push() can also be utilized for array concatenation:

JavaScript
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

arr1.push(...arr2);
// arr1 is now [1, 2, 3, 4, 5, 6]

Using While Loop

For those who enjoy a bit of looping magic, a while loop can elegantly append one array to another:

JavaScript
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

let i = 0;
while (i < arr2.length) {
  arr1.push(arr2[i]);
  i++;
}
// arr1 is now [1, 2, 3, 4, 5, 6]

Using Array.forEach():

Using the power of functional programming, forEach() provides a concise way to iterate over elements and append one array to another:

JavaScript
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

arr2.forEach(element => arr1.push(element));
// arr1 is now [1, 2, 3, 4, 5, 6]

This method excels in scenarios where you want to toggle a class on and off, catering to features like light/dark mode switches.


Using for…of Loop

The for…of loop simplifies the process, offering a clean and readable approach to merge arrays:

JavaScript
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

for (const element of arr2) {
  arr1.push(element);
}
// arr1 is now [1, 2, 3, 4, 5, 6]

Using for Loop

For those who appreciate the classic for loop, it remains a reliable choice for appending arrays:

JavaScript
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

for (let i = 0; i < arr2.length; i++) {
  arr1.push(arr2[i]);
}
// arr1 is now [1, 2, 3, 4, 5, 6]

🧪Practice Coding Problem: Array Merge

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

You are given two arrays, arr1 and arr2, each containing integers. Your task is to merge these arrays into a new array, mergedArray, by alternating elements from each array. The resulting array should maintain the order of elements from both arrays.

Write a function mergeArrays to accomplish this task. The function should take two arrays as input and return the merged array.

JavaScript
function mergeArrays(arr1, arr2) {
// > > > 👉 Write code here 👈 < < <
}


const arr1 = [1, 2, 3];
const arr2 = ['a', 'b', 'c'];

const mergedArray = mergeArrays(arr1, arr2);
console.log(mergedArray);
// Output: [1, 'a', 2, 'b', 3, 'c']
Constraints:
– The input arrays, arr1 and arr2, will have lengths between 1 and 1000.
– The elements of the arrays can be integers, strings, or a mix of both.
Please attempt before seeing the Answer:
JavaScript
function mergeArrays(arr1, arr2) {
  const mergedArray = [];
  const maxLength = Math.max(arr1.length, arr2.length);

  for (let i = 0; i < maxLength; i++) {
    if (i < arr1.length) {
      mergedArray.push(arr1[i]);
    }
    if (i < arr2.length) {
      mergedArray.push(arr2[i]);
    }
  }

  return mergedArray;
}

Function mergeArrays iterates through both input arrays simultaneously, alternating elements and pushing them into the mergedArray. The loop continues until the longer array is fully processed. The resulting array is then returned.


Hope you never break up with Javascript arrays, as you know how to get “pushy” too, and will concatenate the hell out of arrays, anytime ! 😄 Keep coding 💻 🚀

Scroll to Top