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}]
]
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);
A solution in plain Javascript with a single loop without mutating the original array.
var arr = [{ id: 1, code: 0 }, { id: 1, code: 12 }, { id: 1, code: 0 }, { id: 1, code: 0 }, { id: 1, code: 5 }],
grouped = arr.reduce(function (r, a, i) {
var l = r[r.length - 1];
if (!i || l[l.length - 1].code) {
r.push([a]);
} else {
l.push(a);
}
return r;
}, []);
console.log(grouped)
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With