I’ve got a multidimensionnal array like
var a = [['Dog','Cat'],[1,2]];
My goal is to get an array like
var b = [['G','X','G','X'], ['Dog','Dog', 'Cat', 'Cat'],[1,1,2,2]];
For this i’m using a loop but i didn’t get the result i need.
for (i=0;i<a.length;i++){
for (j=0;j<a[i].length;j++){
b[0][j] = 'G';
b[1][j] = a[i][j];
b[0][j] = 'X';
b[1][j] = a[i][j];
}
}
I try to insert the value of a array to b array but i need to duplicate each value and insert a ‘G’ next a ‘X’
It should be (not sure it is correct)
b[] = ['G'],[a[0][0]],[a[1][0]]
b[] = ['X'],[a[0][0]],[a[1][0]]
b[] = ['G'],[a[0][1]],[a[1][1]]
b[] = ['X'],[a[0][1]],[a[1][1]]
>Solution :
If I did understand you correct and you need to duplicate your data in array a and alternate ‘G’ and ‘X’ in your target array b, then you could do something like that:
var a = [['Dog','Cat'],[1,2]];
var b = [[],[],[]];
for (i = 0; i < a[0].length; ++i){
for (j = 0; j < 2; ++j) {
b[0][i * 2 + j] = j === 0 ? 'G' : 'X';
b[1][i * 2 + j] = a[0][i];
b[2][i * 2 + j] = a[1][i];
}
}