Home > Mobile >  how can I dynamically create an array of arrays?
how can I dynamically create an array of arrays?

Time:09-16

I would like to dynamically create an array of numbers from 1 to 100 which contains 4 arrays each containing 5 arrays containing 5 numbers. example:

[
[[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]],
[[26,...,30],[31,...,35],[36,...,40],[41,..,45],[46,...,50]],
[[51,...55],[56,...60],[61,...,65],[66,...,70],[71,..,75]],
[[76,...,80],[81,...,85],[86,...,90],[91,...95],[96,...100]]
]

CodePudding user response:

try this:

function chunk (items, size) {  
  const chunks = []
  items = [].concat(...items)

  while (items.length) {
    chunks.push(
      items.splice(0, size)
    )
  }

  return chunks
}

and then

chunk(Array.from({length: 100}, (_, i) => i   1),5)

CodePudding user response:

Interesting problem. You can use reduce() to group items into nested arrays of a given size.

My approach below: first create an array of numbers that increment from 1 to 100. Then, use reduce() to group them into 20. Finally, use .map() and .reduce() together to group the nested arrays into groups of 5.

const chunk = (values, chunkSize) => 
   values.reduce((accum, val) => {
    const lastGroup = accum[accum.length - 1];
    const isFull = lastGroup.length === chunkSize;
    if (isFull) { return [...accum, [val]]; }
    return [...accum.slice(0,-1), [...lastGroup, val]];
  }, [[]]);

const oneDimList = Array.from({ length: 100 }, (val, index) => index   1);
const twoDimList = chunk(oneDimList, 20);
const threeDimList = twoDimList.map(nestedArr => chunk(nestedArr, 5));

console.log(threeDimList);

  • Related