Home > Back-end >  How to set a multiple arrays in javascript
How to set a multiple arrays in javascript

Time:05-07

I run into a problem wherein I want to divide my items in by array likes this

[ 
 1 [ 1[[1][2]]  2[[3][4][5]] ],  2[ 1[[1][2]]  2[[3][4][5]]],  
 3 [ 1[[1][2]] 2[[3][4][5]]],  4[ 1[[1][2]]  2[[3][4][5]]]  
]

So basically in the first 1,2,3,4 array are the object array of the arrays... It can basically express like this

  • Array parrent [ 1 2 3 4 ]
    • Second array parent [ 1 2 ]
      • First third array [ 1 2 ]
      • Second third array [ 3 4 5 ]

In my code it is something like this

    for (let i = 1;i < 4 ;i  ) {
        const list = []
        for (let j = 1; j < 16*i ; j  ) {
            var list2 = []
            if (j % 5 == 0) {
                const list3 = []
                const list4 = []
                for (let k = 0; k < j; k  ) {
                    if (k <= 1) {
                        list3.push(`/kgfpics/kgf${k}.png`)
                    } else if ( k >= 4) {
                        list4.push(`/kgfpics/kgf${k}.png`)
                    }
                    list2.push(list3,list4)
                }
                list.push(list2)
            }
        }
        // 1 [ 1 [ [1],[2] ] , 2 [ [3],[4],[5] ] ]
        topiclist.push(list)  
    }
    console.log(topiclist)

but the expectation result that I want to happen is not working...Can you notice where I am wrong here? Cause I wanna done my problem for this my project. Thank you very much.

CodePudding user response:

Hopefully I've understood your desired result. You could hardcode the keys/indices you want to map until the most inner loop where they are finally mapped to the path values.

let k = 1;
const res = Array.from({ length: 4 }).map(() =>
  Array.from({ length: 2 }).map(() =>
    [2, 3].map((length) =>
      Array.from({ length }).map(() => `/kgfpics/kgf${k  }.png`)
    )
  )
);

console.log(res);

  • Related