最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to partition array into multiple groups using Lodash? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited May 23, 2017 at 10:31 CommunityBot 11 silver badge asked Jul 28, 2015 at 18:39 Justin MaatJustin Maat 1,9753 gold badges23 silver badges33 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 16

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();
发布评论

评论列表(0)

  1. 暂无评论