I have 2 arrays, say arr1=[A,B,C,D];
and arr2= [a,b,c,d];
I want to create a third array by combining these 2 in the following way:
arr3= [A,a,B,b,C,c,D,d];
How can I achieve this using jquery? Please help!
To merge any two array in C programming, start adding each and every element of the first array to the third array (target array). Then start appending each and every element of the second array to the third array (target array) as shown in the program given below.
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
In order to merge two arrays, we find its length and stored in fal and sal variable respectively. After that, we create a new integer array result which stores the sum of length of both arrays. Now, copy each elements of both arrays to the result array by using arraycopy() function.
Given two arrays arr1[] and arr2[], we need to combine two arrays in such a way that the combined array has alternate elements of both. If one array has extra element, then these elements are appended at the end of the combined array.
Try to use jquery's $.merge(array1,array2)
function,
var arr3 = $.merge( arr1, arr2 )
For the format you have asked,
var arr1=['A','B','C','D'];
var arr2=['a','b','c','d'];
var arr3 = [];
for(var i=0,len=arr1.length;i<len;i++){
arr3[arr3.length] = arr1[i];
arr3[arr3.length] = arr2[i];
}
alert(arr3);
If you just want to alternate elements between the two arrays, and that they're always equal in length:
arr3 = [];
for (var i=0,j=arr1.length; i<j; i++) {
arr3.push(arr1[i]);
arr3.push(arr2[i]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With