Chris
Chris

Reputation: 1027

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.

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]]

Upvotes: 0

Views: 50

Answers (2)

Portevent
Portevent

Reputation: 744

In order to solve that problem easly, I'll break it down in two part. First is duplicating the line, and then inserting the GXGXGXGX...

Step 1 : duplicate the lines

Answered here : How to duplicate elements in a js array?

function duplicate(item){
    return [item, item]
}

var a = [['Dog','Cat'],[1,2]];
// For each list inside a, duplicate the element of that sublist
var b = a.map(sublistOfNumberOrPet => sublistOfNumberOrPet .flatMap(duplicate))
// b = [['Dog','Dog', 'Cat', 'Cat'],[1,1,2,2]]

Step 2 : Add G X G X...

We will build a list of G, X, G, X to append to b

b = [['Dog','Dog', 'Cat', 'Cat'],[1,1,2,2]]
// Create a new array, the same length as the first element of b
// And fill it with `G` and `X` (if index is odd : `G`, else `X`)
gxgx = Array.from({length: b[0].length}, (x, index) => index%2?'G':'X');

// Append our gxgx inside `b (unshift add it in the first place)
b.unshift(gxgx)

More informations about unshift

Upvotes: 0

RowBlaBla
RowBlaBla

Reputation: 34

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];
    }
}

Upvotes: 1

Related Questions