0

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]] 
5
  • 1
    What's the process to get from your first array to your second? If you describe all the steps/requirements it will be considerably easier for people to help. Commented Oct 19, 2022 at 9:15
  • can you change this requirement at all or are you stuck with it. Commented Oct 19, 2022 at 9:33
  • Will the child arrays always contain the same number of elements? Commented Oct 19, 2022 at 9:35
  • I can change. The idea is to get an array with the G and X value. Commented Oct 19, 2022 at 9:36
  • Yes they will contains the same number of element. Commented Oct 19, 2022 at 9:37

2 Answers 2

1

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]; } } 
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.