Saturday, September 21, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Program to Merge Two Arrays Without Creating a New Array

JavaScript Program to Merge Two Arrays Without Creating a New Array

In this article, we will learn how to merge two arrays without creating a new array. In JavaScript Array is used to store elements of similar data types. If we want to add an element into another array for merging two arrays, we can use the push method. There are many methods for merging two arrays without creating a new array.

Method 1: Using the push() method

We can use the ‘push’ method to insert one array into another and merge the two arrays. This approach will modify the first array in place and won’t create a new array.

Example: In the below example we are using .push to merge to arrays.

Javascript




const fruit1 = ['Mango', 'Apple', 'Orange'];
const fruit2 = ['Banana', 'Avacado', 'Watermelon'];
  
fruit2.forEach((element) => {
    fruit1.push(element);
});
  
console.log(fruit1);


Output

[ 'Mango', 'Apple', 'Orange', 'Banana', 'Avacado', 'Watermelon' ]

Method 2: Using splice() Method

The JavaScript Array splice() Method is an inbuilt method in JavaScript that is used to modify the contents of an array by removing the existing elements and/or by adding new elements.

Example: In below example we are using splice method to merge two arrays.

Javascript




const array1 = ['US', 'London', 'Europe'];
const array2 = ['Japan', 'Spain', 'Australia'];
array1.splice(array1.length, 0, ...array2);
console.log(array1);


Output

[ 'US', 'London', 'Europe', 'Japan', 'Spain', 'Australia' ]

Method 3: By using push.apply method

In this method, we will use apply() method with array.push() for merging two arrays without creating new arrays.

Example: In below example we are using ‘push.apply’ method to merge two arrays.

Javascript




const array1 = ["HTML", "CSS", "JAVA"];
const array2 = ["PYTHON", "JAVASCRIPT", ".NET"];
Array.prototype.push.apply(array1, array2);
console.log(array1);


Output

[ 'HTML', 'CSS', 'JAVA', 'PYTHON', 'JAVASCRIPT', '.NET' ]
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments