使用 reduce 将数组分为几个部分,每个部分最多10个!
相比其他语言使用 js 实现这个逻辑非常的简单方便!
var packageIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 1, 5, 5, 23, 23, 23, 2, 32, 4, 2, 5, 34, 2]; var step = 10; var group = packageIds.reduce((total, current, index) => { if (index == 1) { //init 第一次 total 是1 current 是 2 if (step == 1) { total = [[total],[ current]]; } else { total = [[total, current]]; } }else{ var last = total[total.length - 1]; if (last.length < step) { last.push(current); } else { total.push([current]); } } return total; });
打印出来看下效果: