Shlomi Schwartz Shlomi Schwartz - 3 months ago 8
Javascript Question

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

Given the following array:

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


How can I use lodash, to split the array each time code is not equal to 0 and get the following results?

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

Answer

You can use Array.prototype.reduce (or lodash's _.reduce()) for this:

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

Comments