1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS
1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS

Merging Arrays in JavaScript: A Comprehensive Guide

ReadTime: 5 minutes

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)
Spread syntax to combine arrays

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]
Array.concat() to concatenate arrays

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]
Array.push() to concatenate array

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]
While loop to append arrays

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]
Array.forEach() to iterate and append array

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]
for...of loop to merge arrays

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]
for loop to append arrays

🧪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.

Problem (JavaScript)

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']
Problem Code

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:

Solution
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;
}
Solution Code

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 💻 🚀

Contact

Feel free to reach out!