如何使用 Lodash 将数组分成多个组?

How to partition array into multiple groups using Lodash?

我正在尝试找到一种基于谓词将对象数组划分为数组组的简明方法。

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'}
];

我看到 , 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 通过键将它分组到一个对象中,我正在寻找相同的但在数组中(没有键)。

是否有更简单的方法来嵌套几个 lodash 函数来实现此目的?

您可以先按 id 分组,这将生成一个对象,其中键是 id 的不同值,值是具有该 ID 的所有数组项的数组,即基本上是你想要的(使用 _.values() 来获取值数组):

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

// chained version
var partitionedById = _(arr).groupBy('id').values().value();