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?

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! wasn't aware of the _.values() function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.