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

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

    You could use the remainder of the index with the wanted size for the index and push the value.

    var array = [1, 2, 3, 4, 5, 6],
        size = 3,
        result = array.reduce((r, v, i) => {
            var j = i % size;
            r[j] = r[j] || [];
            r[j].push(v);
            return r;
        }, []);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题