OneBite.Dev - Coding blog in a bite size

merge two array in javascript

Code snippet for how to how to merge two array in javascript with sample and detail explanation

Javascript is a dynamic computer programming language that supports arrays for more versatility and fast processing. In this simple and easy-to-follow tutorial, we are going to talk about merging two arrays in JavaScript.

Code snippet for merging arrays

Below is a simple code snippet in JavaScript for merging two arrays:

let array1 = ["Apple", "Banana", "Mango"];
let array2 = ["Orange", "Peach", "Blueberry"];
let mergedArray = [...array1, ...array2];
console.log(mergedArray);

Code Explanation for merging arrays

Let’s break down the above code snippet line by line to understand how it works:

  1. The first line, let array1 = ["Apple", "Banana", "Mango"]; , defines the first array named “array1” which consists of three elements.

  2. The second line, let array2 = ["Orange", "Peach", "Blueberry"]; defines the second array named “array2” with another set of three elements.

  3. The third line, let mergedArray = [...array1, ...array2]; is where the merging of the two arrays occurs. The ... operator, also known as the spread operator, is used here. What this operator does is that it spreads out elements of iterable objects (like arrays or strings) into multiple elements. Hence, ...array1 and ...array2 individually spread out the elements of “array1” and “array2”. Then, by combining these, a new array containing all the elements from the two previous arrays is created, and this new array is stored in the “mergedArray” variable.

  4. Finally, the last line, console.log(mergedArray); simply prints the “mergedArray” to the console, so you see the output as - ["Apple", "Banana", "Mango", "Orange", "Peach", "Blueberry"]

That’s it! This is a simple demonstration of how to merge two arrays in JavaScript using the spread operator. It’s a concise and efficient approach to combine arrays and can be used with any number of arrays.

javascript