JavaScript : How to Merge Arrays with Contents

Java Script @ Freshers.in

In this tutorial, we will explore various methods to merge arrays, with a specific focus on arrays containing elements. Through practical examples and detailed explanations, you will learn how to effectively merge arrays and leverage this skill in your JavaScript projects.

1. The concat() Method

The concat() method is a classic approach to merge arrays in JavaScript. It returns a new array containing the elements of the original arrays concatenated together in the order they appear.

2. The Spread Operator

The spread operator (…) is a concise and modern way to merge arrays. It allows you to expand elements from one or more arrays directly into a new array. Here’s how to use the spread operator for merging arrays:

const array1 = ["freshers_in_JS", "freshers_in_WebDev"];
const array2 = ["freshers_in_DataScience", "freshers_in_UIUX"];
const mergedArray = [...array1, ...array2];
console.log(mergedArray);
// Output: ["freshers_in_JS", "freshers_in_WebDev", "freshers_in_DataScience", "freshers_in_UIUX"]

3. The push() Method

The push() method is commonly used to add elements to the end of an array. By combining it with the spread operator, we can merge arrays effectively:

const array1 = ["freshers_in_JS", "freshers_in_WebDev"];
const array2 = ["freshers_in_DataScience", "freshers_in_UIUX"];
array1.push(...array2);
console.log(array1);
// Output: ["freshers_in_JS", "freshers_in_WebDev", "freshers_in_DataScience", "freshers_in_UIUX"]

4. The splice() Method

The splice() method allows us to modify an array by adding or removing elements. When used for merging arrays, it can insert elements from one array into another:

const array1 = ["freshers_in_JS", "freshers_in_WebDev"];
const array2 = ["freshers_in_DataScience", "freshers_in_UIUX"];
array1.splice(array1.length, 0, ...array2);
console.log(array1);
// Output: ["freshers_in_JS", "freshers_in_WebDev", "freshers_in_DataScience", "freshers_in_UIUX"]

The concat() method provides a traditional approach, while the spread operator (…) offers a more modern and concise alternative. Additionally, combining the push() and splice() methods with the spread operator provides in-place merging options.

Get more articles on Java Script

Author: user

Leave a Reply