Shl*_*rtz 5 javascript arrays chunks web lodash
给定以下数组:
var arr = [{id:1 , code:0},
{id:1 , code:12},
{id:1 , code:0},
{id:1 , code:0},
{id:1 , code:5}];
Run Code Online (Sandbox Code Playgroud)
如何使用 lodash,在每次代码不等于 0 时拆分数组并获得以下结果?
[
[{id:1 , code:0},{id:1 , code:12}],
[{id:1 , code:0},{id:1 , code:0},{id:1 , code:5}]
]
Run Code Online (Sandbox Code Playgroud)
您可以使用Array.prototype.reduce(或 lodash's _.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);Run Code Online (Sandbox Code Playgroud)