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

后端 未结 3 1866
梦毁少年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:03

    You can use the following code:

    function chunkArray(myArray, chunk_size) {
        let results = new Array(chunk_size);
        for(let i = 0; i < chunk_size; i++) {
            results[i] = []
        }
        // append arrays rounding-robin into results arrays.
        myArray.forEach( (element, index) => { results[index % chunk_size].push(element) });
        return results;
    }
    
    const array = [1,2,3,4,5,6];
    const result = chunkArray(array, 3)
    console.log(result)

提交回复
热议问题