Let's say I have an array like this one:
[
{ product: '...', price: 12 },
{ product: '...', price: 12 },
{ product: '...', price: 14 },
{ product: '...', price: 12 }
]
I'd like to group this array by price and by using lodash's groupBy I'd get below result:
[
12: [
{ product: '...', price: 12 },
{ product: '...', price: 12 },
{ product: '...', price: 12 }
],
14: [
{ product: '...', price: 14 }
]
]
Nice, but I'd like to have an array of three arrays because I want to save some kind of the same order like in the start array. I'd like to have this result:
[
[
{ product: '...', price: 12 },
{ product: '...', price: 12 }
],
[
{ product: '...', price: 14 }
],
[
{ product: '...', price: 12 }
]
]
Is there a function for this?
You can do something like this using lodash -
var count = 0;
console.log(
_.values(_.groupBy(_.map(myArray, (item, index) => {
if(index == 0) return _.merge(item, { group : 0});;
if( myArray[index-1].price == item.price )
return _.merge(item, { group : count});
return _.merge(item, { group : ++count});
}
), 'group'))
);
Try it here - lodash-group-consequtive
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