使用对象 属性 作为 "delimiter" 的对象数组块

Chunks of an Array of objects using an object property as the "delimiter"

给定以下数组:

var arr = [{id:1 , code:0},
           {id:1 , code:12},
           {id:1 , code:0},
           {id:1 , code:0},
           {id:1 , code:5}];

如何使用 lodash,每次 code 不等于 0 时拆分数组并得到以下结果?

[
 [{id:1 , code:0},{id:1 , code:12}],
 [{id:1 , code:0},{id:1 , code:0},{id:1 , code:5}]
]

你可以使用 Array.prototype.reduce(或 lodash 的 _.reduce()):

var arr = [{id:1 , code:0},
           {id:1 , code:12},
           {id:1 , code:0},
           {id:1 , code:0},
           {id:1 , code:5}];

var result = arr.reduce(function(result, item, index, arr) {
  index || result.push([]); // if 1st item add sub array
  
  result[result.length - 1].push(item); // add current item to last sub array
  
  item.code !== 0 && index < arr.length - 1 && result.push([]); // if the current item code is not 0, and it's not the last item in the original array, add another sub array
  
  return result;
}, []);

console.log(result);

另一种 "native" JS 解决方案使用 Array.splice 函数:

var arr = [{id:1 , code:0},{id:1 , code:12}, {id:1 , code:0},{id:1 , code:0}, {id:1 , code:5}],
    chunks = [];

for (var i = 0; i < arr.length; i++) {
    arr[i].code !== 0 && chunks.push(arr.splice(0, i + 1));
}

console.log(JSON.stringify(chunks, 0, 4));

一个简单的 Javascript 解决方案,只有一个循环而不改变原始数组。

var arr = [{ id: 1, code: 0 }, { id: 1, code: 12 }, { id: 1, code: 0 }, { id: 1, code: 0 }, { id: 1, code: 5 }],
    grouped = arr.reduce(function (r, a, i) {
        var l = r[r.length - 1];
        if (!i || l[l.length - 1].code) {
            r.push([a]);
        } else {
            l.push(a);
        }
        return r;
    }, []);

console.log(grouped)
.as-console-wrapper { max-height: 100% !important; top: 0; }

结果是,如果您希望减少元素数量,那么我想您只需要减少即可。

var arr = [{id:1 , code:0},
           {id:1 , code:12},
           {id:1 , code:0},
           {id:1 , code:0},
           {id:1 , code:5}],
reduced = arr.reduce((red,obj) => !obj.code ? red[red.length-1].length === 1 ||
                                              red[red.length-1].length === 0 ? (red[red.length-1].push(obj),red)
                                                                             : red.concat([[obj]])
                                            : (red[red.length-1].push(obj),red),[[]]);
console.log(reduced);