Dil85 - 1 year ago 74
Javascript Question

# Combine two arrays

I have two array which is like to be

``````var array1=['a1','a2','a3','a4','a5,','a6','a7','a8','a9','a10,','a11','a12'----];
var array2=['b1','b2','b3','b4',----];
var result= [];
``````

I want to show result array is

``````result= ['a1','a2','b1','a3','a4,','a5','a6','a7','a8','a9,','a10','a11','b2','a12']
``````

second array array2 placed in the position of 3,12,19,28,35..(series like 3,3+9,12+7,19+9,28+7--)
If array1 has less value than array2 placed continuously for eg:

``````array1=['a1','a2','a3'];
array2=['b1','b2','b3'];
``````

then

``````result=['a1','a2','b1','a3','b2','b3'];
``````

How to implement this by using jquery?

Fast way to manage this. But it could be optimized.

``````var array1=['a1','a2','a3','a4','a5,','a6','a7','a8','a9','a10,','a11','a12'];
var array2=['b1','b2','b3','b4'];
document.body.innerHTML += "arr1:" + array1 + "<br/>";
document.body.innerHTML += "arr2:" + array2 + "<br/>";
var result= [];

var index=0;
var lastInsertedBindex=0;
var step1 = 9;
var step2 = 7;
var lastUsedStep = step2;
var nextStepIndex = 3;
elements = true;
var indexFromA = 0;
var indexFromB = 0;
var elementsExists = true;
do{
if( index != nextStepIndex ){
if( undefined != array1[indexFromA] ){
result.push( array1[indexFromA]);
indexFromA++;
} else if( undefined != array2[indexFromB]){
result.push( array2[indexFromB]);
indexFromB++;
} else
elementsExists = false;

index++;
continue;
}else{
if( undefined != array2[indexFromB] ){
result.push(array2[indexFromB]);
indexFromB++;
lastUsedStep = lastUsedStep == step1 ? step2 : step1;
nextStepIndex = nextStepIndex + lastUsedStep;
} else if( undefined != array1[indexFromA]) {
result.push(array1[indexFromA]);
indexFromA++;

} else
elementsExists = false;

index++;
}

}while(elementsExists);
document.body.innerHTML += "res:" + result;``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download