13

I'm trying to find a concise way to partition an array of objects into groups of arrays based on a predicate.

var arr = [
  {id: 1, val: 'a'}, 
  {id: 1, val: 'b'}, 
  {id: 2, val: 'c'}, 
  {id: 3, val: 'a'}
];

//transform to below

var partitionedById = [
  [{id: 1, val: 'a'}, {id: 1, val:'b'}], 
  [{id: 2, val: 'c'}], 
  [{id: 3, val: 'a'}
];

I see this question , which gives a good overview using plain JS, but I'm wondering if there's a more concise way to do this using lodash? I see the partition function but it only splits the arrays into 2 groups (need it to be 'n' number of partitions). The groupBy groups it into an object by keys, I'm looking for the same but in an array (without keys).

Is there a simpler way to maybe nest a couple lodash functions to achieve this?

Community
  • 1
  • 1
Justin Maat
  • 1,965
  • 3
  • 23
  • 33

1 Answers1

17

You can first group by id, which will yield an object where the keys are the different values of id and the values are an array of all array items with that id, which is basically what you want (use _.values() to get just the value arrays):

// "regular" version
var partitionedById = _.values(_.groupBy(arr, 'id'));

// chained version
var partitionedById = _(arr).groupBy('id').values().value();
robertklep
  • 198,204
  • 35
  • 394
  • 381