Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combine two arrays and create a third array using jquery

Tags:

jquery

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!

like image 774
user3641092 Avatar asked May 15 '14 13:05

user3641092


People also ask

How do I merge two arrays in third array?

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.

How do I combine two arrays into a new array?

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.

How do I combine two arrays?

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.

How do I combine two arrays alternatively?

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.


2 Answers

Try to use jquery's $.merge(array1,array2) function,

var arr3 = $.merge( arr1, arr2 )

DEMO

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);

DEMO I

like image 149
Rajaprabhu Aravindasamy Avatar answered Oct 03 '22 02:10

Rajaprabhu Aravindasamy


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]);
}
like image 45
Blazemonger Avatar answered Oct 03 '22 00:10

Blazemonger