编程语言
首页 > 编程语言> > javascript-使用对象属性作为“定界符”的对象数组的块

javascript-使用对象属性作为“定界符”的对象数组的块

作者:互联网

给定以下数组:

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);

标签:chunks,web,lodash,arrays,javascript
来源: https://codeday.me/bug/20191118/2026582.html