How to Merge Arrays in JavaScript: Array Concatenation in JS

Estimated read time 2 min read

Introduction

In JavaScript, arrays are fundamental data structures that allow you to store and manipulate collections of elements. There are situations where you may need to combine or merge multiple arrays into a single array. This process is known as array concatenation. In this tutorial, we will explore different methods to merge arrays in JavaScript.

Prerequisites

Before we dive into array concatenation, make sure you have a basic understanding of JavaScript and its array manipulation capabilities. It’s also helpful to have a JavaScript development environment set up.

Method 1: Using the Concat Method

The concat() method in JavaScript is a convenient way to merge two or more arrays. It creates a new array by concatenating the elements of the existing arrays. Here’s an example:

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = array1.concat(array2);

console.log(mergedArray);

In this example, we have two arrays array1 and array2. We use the concat() method to merge them into a new array called mergedArray. The resulting array [1, 2, 3, 4, 5, 6] is then logged to the console.

Method 2: Using the Spread Operator

The spread operator (...) is another powerful feature in JavaScript that can be used to merge arrays. It allows us to expand an array into individual elements, which can then be used to create a new array. Here’s an example:

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = [...array1, ...array2];

console.log(mergedArray);

In this example, we use the spread operator to merge array1 and array2 into mergedArray. The result is the same as the previous example: [1, 2, 3, 4, 5, 6].

Method 3: Using the Push Method

If you want to merge arrays in-place without creating a new array, you can use the push() method. This method allows you to add the elements of one array to another array. Here’s an example:

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
array1.push(...array2);

console.log(array1);

In this example, we use the push() method along with the spread operator to add the elements of array2 to array1. As a result, array1 is modified and contains the merged elements: [1, 2, 3, 4, 5, 6].

Method 4: Using the Apply Method

The apply() method is an alternative way to merge arrays. It is a legacy method inherited from earlier versions of JavaScript. Here’s an example:

Mark Stain

My name is Mark Stein and I am an author of technical articles at EasyTechh. I do the parsing, writing and publishing of articles on various IT topics.

You May Also Like

More From Author

+ There are no comments

Add yours