Reputation: 8913
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}]
]
Upvotes: 5
Views: 2050
Reputation: 191986
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);
Upvotes: 4
Reputation: 26161
Well in the result if you expect reduced number elements then i guess you just have to reduce.
var arr = [{id:1 , code:0},
{id:1 , code:12},
{id:1 , code:0},
{id:1 , code:0},
{id:1 , code:5}],
reduced = arr.reduce((red,obj) => !obj.code ? red[red.length-1].length === 1 ||
red[red.length-1].length === 0 ? (red[red.length-1].push(obj),red)
: red.concat([[obj]])
: (red[red.length-1].push(obj),red),[[]]);
console.log(reduced);
Upvotes: 0
Reputation: 386654
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; }
Upvotes: 3
Reputation: 92854
An alternative "native" JS solution using Array.splice
function:
var arr = [{id:1 , code:0},{id:1 , code:12}, {id:1 , code:0},{id:1 , code:0}, {id:1 , code:5}],
chunks = [];
for (var i = 0; i < arr.length; i++) {
arr[i].code !== 0 && chunks.push(arr.splice(0, i + 1));
}
console.log(JSON.stringify(chunks, 0, 4));
Upvotes: 0