给定以下数组:
var arr = [{id:1 , code:0},
{id:1 , code:12},
{id:1 , code:0},
{id:1 , code:0},
{id:1 , code:5}];
我如何使用lodash在每次代码不等于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);