Js 数组按数量分部!

使用 reduce 将数组分为几个部分,每个部分最多10个!

https://www.cnblogs.com/zhuwansu/p/13036358.html 这个版本更简单

相比其他语言使用 js  实现这个逻辑非常的简单方便!

var group = function (source, step) { 
        if (source.length == 1) return [source];//这个情况要单独写一下
        var group = source.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;
        });
        return group;
    }
    var source =  [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;
    console.log(group(source,step))

打印出来看下效果:

  1. 0: (10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  2. 1: (10) [11, 12, 13, 14, 1, 5, 5, 23, 23, 23]
  3. 2: (7) [2, 32, 4, 2, 5, 34, 2]

原文地址:https://www.cnblogs.com/zhuwansu/p/11163966.html