编辑代码

// _.chunk(['a', 'b', 'c', 'd'], 2);
// // => [['a', 'b'], ['c', 'd']]

// _.chunk(['a', 'b', 'c', 'd'], 3);
// // => [['a', 'b', 'c'], ['d']]

// _.chunk(['a', 'b', 'c', 'd'], 5);
// // => [['a', 'b', 'c', 'd']]

// _.chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 2);
// // => [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g']]

// _.chunk(['a', 'b', 'c', 'd'], 0);
// => []
// 数组分块
console.log(chunk(['a', 'b', 'c', 'd'], 2))
function chunk(input, size) {
    if(size===0) return []
    let accumulate = 0
    let cur = []
    let res = []
    input.forEach((x)=>{
        accumulate++
        cur.push(x)
        if(accumulate === size){
            res.push([...cur])
            accumulate = 0
            cur = []
        }
    })

    if(cur.length){
        res.push([...cur])
    }
    return res
}