![]() |
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. Table of Content Method 1: Using the push() methodWe 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.
Output [ 'Mango', 'Apple', 'Orange', 'Banana', 'Avacado', 'Watermelon' ] Method 2: Using splice() MethodThe 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.
Output [ 'US', 'London', 'Europe', 'Japan', 'Spain', 'Australia' ] Method 3: By using push.apply methodIn 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.
Output [ 'HTML', 'CSS', 'JAVA', 'PYTHON', 'JAVASCRIPT', '.NET' ] Method 4: Using concat with AssignmentThe concat method is typically used to merge arrays and returns a new array. However, by assigning the result back to the original array, we can merge the arrays without explicitly creating a new array. Example: In the below example, we are using concat with assignment to merge two arrays.
Output [ 'Red', 'Blue', 'Green', 'Yellow', 'Purple', 'Orange' ] |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |