JavaScript: Merge Two Arrays

1. Introduction

Combining data sets, or in simpler terms, merging arrays, is a frequently needed operation in programming. JavaScript makes this task very intuitive using the spread operator or the concat() method. In this article, we will look at how to merge two arrays in JavaScript.

2. Program Overview

For this guide, our steps are:

1. Initialize two separate arrays.

2. Merge the arrays using the spread operator.

3. Display the merged array.

3. Code Program

let array1 = [1, 2, 3];   // First array
let array2 = [4, 5, 6];   // Second array
let mergedArray;   // Variable to store the merged array

// Using the spread operator to merge the arrays
mergedArray = [...array1, ...array2];

console.log("First Array:", array1);
console.log("Second Array:", array2);
console.log("Merged Array:", mergedArray);

Output:

First Array: [1, 2, 3]
Second Array: [4, 5, 6]
Merged Array: [1, 2, 3, 4, 5, 6]

4. Step By Step Explanation

1. Array Initialization: We begin by initializing two separate arrays array1 and array2.

2. Merging using the Spread Operator: The spread operator (...) is a nifty ES6 feature. By prefixing an array with ..., we can "spread" its elements into individual elements. By doing so consecutively for array1 and array2, we effectively merge the two arrays.

3. Storing and Displaying the Result: The combined array is stored in the mergedArray variable. Finally, console.log is used to display the original arrays and the resultant merged array.

Comments