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);
上一篇:javascript – 使用下划线或lodash将一个JSON结构转换为另一个


下一篇:python+ pyqt5 实现最简单的计算器