Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

js/lodash divide array basing on object property

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?

like image 235
elzoy Avatar asked Oct 21 '25 12:10

elzoy


1 Answers

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

like image 55
anshulk Avatar answered Oct 23 '25 02:10

anshulk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!