Hello reader's, Today in my blog I will discuss about the merging an array using JavaScript.
Basically the term “Merge” means to combine or join two array into a single array.
In JavaScript , for merging arrays it uses concat method , which produces a new array.
The variables in JavaScript are passed by reference , by using concat ( ) which results in mess .
So , if in our code we want to merge a second array into an existing array , we can use this code :-
var array1 = [1, 2, 3]; var array2 = [4, 5, 6]; Array.prototype.push.apply(array1, array2); console.log(array1); // is: [1, 2, 3, 4, 5, 6]
In the above example , we have taken two arrays containing the desired values in it.
With the help of array.prototype.push.apply method , we can easily merge the two arrays .
Push( ) Method :-
The push( ) method helps to add one or more elements to the end of an array and a new length of an array gets returned.
This method it can be used with call( ) or apply( ) method on the objects that are resembling to an array.
Basically the push( ) method relies on the length property which is used to determine where to insert the given values in the document.
Below is an example to show the use of push( ) method :-
var sports = ['soccer', 'baseball'];
var total = sports.push('football', 'swimming');
console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
console.log(total); // 4
In this code, we have created an array with the name as sport having two values in it.
On creating the variable total , with the help of push method I have inserted two more values to the existing array.
Below is a code displaying the apply( ) method :-
var vegetables = ['parsnip', 'potato'];
var moreVegs = ['celery', 'beetroot'];
// Merge the second array into the first one
// Equivalent to vegetables.push('celery', 'beetroot');
Array.prototype.push.apply(vegetables, moreVegs);
console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']
In the above code , I have used apply( ) method to push all elements from a second array into the first one .
Conclusion:-
Hence, with the help of simple example we can easily merge two array in JavaScript.
Note:- The above method is browser supportable in Chrome1.0 , Firefox1.0, I.E 5.5 , Opera and Safari .
0 Comment(s)