Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add value and duplicate item in multidimensionnel array?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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];
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading