How can I split an array into chunks but have it fill each array by going one by one

后端 未结 3 1839
梦毁少年i
梦毁少年i 2021-01-14 19:25

I\'m using this function to create chunks of an array:

function chunkArray(myArray, chunk_size) {
    let results = [];
    while (myArray.length) {
                


        
3条回答
  •  星月不相逢
    2021-01-14 20:26

    I'd do something like this:

    function chunkArray(src, chunkSize ) {
      const chunks = Math.ceil( src.length / chunkSize );
      const chunked = [];
    
      for (let i = 0; i < src.length; ++i) {
        const c       = i % chunks;
        const x       = chunked[c] || (chunked[c]=[]);
        x[ x.length ] = src[i];
      }
    
      return chunked;
    }
    

提交回复
热议问题