
大家好,使用数据我是进行 ConardLi ,今天我们一起来看一个数据分组的分组方式小技巧。
对数据进行分组,最优是使用数据我们在开发中经常会遇到的需求,使用 JavaScript 进行数据分组的进行方式也有很多种,但是分组方式由于没有原生方法的支持,我们自己实现的最优数据分组函数通常都比较冗长而且难以理解。
不过,使用数据告诉大家一个好消息,进行一个专门用来做数据分组的分组方式提案 Array.prototype.groupBy 已经到达 Stage 3 啦!

在看这个提案,服务器托管之前,最优我们先来回顾下我们以前在 JavaScript 里是使用数据怎么分组的。
以前的进行方式
假设我们有下面一组数据:
const items = [ { type: clothes, value: 👔, }, { type: clothes, value: 👕, }, { type: clothes, value: 👗, }, { type: animal, value: 🐷, }, { type: animal, value: 🐸, }, { type: animal, value: 🐒, }, ]; 我们希望按照 type 分组成下面的格式:
const items = { clothes: [ { type: clothes, value: 👔, }, { type: clothes, value: 👕, }, { type: clothes, value: 👗, }, ], animal: [ { type: animal, value: 🐷, }, { type: animal, value: 🐸, }, { type: animal, value: 🐒, }, ], }; 我们可能会用到下面的写法:
for 循环
最直接而且容易理解的方法,就是分组方式代码有点多。
const groupedBy = { }; for (const item of items) { if (groupedBy[item.type]) { groupedBy[item.type].push(item); } else { groupedBy[item.type] = [item]; } } reduce
使用 Array.protoype.reduce 虽然语法看起来简单,但是太难读了。
items.reduce( (acc, item) => ({ ...acc, [item.type]: [...(acc[item.type] ?? []), item], }), { }, ); 我们稍微改造的容易理解一点,语法就跟上面的 for 循环差不多了:
items.reduce((acc, item) => { if (acc[item.type]) { acc[item.type].push(item); } else { acc[item.type] = [item]; } return acc; }, { }); filter
使用 Array.prototype.filter,代码看起来很容易阅读,香港云服务器但是性能很差,你需要对数组进行多次过滤,而且如果 type 属性值比较多的情况下,还需要做更多的 filter 操作。
const groupedBy = { fruit: items.filter((item) => item.type === clothes), vegetable: items.filter((item) => item.type === animal), }; 其他
如果你既不想用 reduce,还想用到函数式写法,你可能会写出下面的代码:
Object.fromEntries( Array.from(new Set(items.map(({ type }) => type))).map((type) => [ type, items.filter((item) => item.type === type), ]), ); 是不是很让人崩溃 🤯~
Array.prototype.groupBy
好了,如果使用 Array.prototype.groupBy,你只需要下面这一行代码:
items.groupBy(({ type }) => type); groupBy 的回调中一共有三个参数:
参数1:数组遍历到的当前对象 参数2:index 索引 参数3:原数组 const array = [1, 2, 3, 4, 5]; // groupBy groups items by arbitrary key. // In this case, were grouping by even/odd keys array.groupBy((num, index, array) => { return num % 2 === 0 ? even: odd; }); 另外,你还可以用 groupByToMap,将数据分组为一个 Map 对象。亿华云
// groupByToMap returns items in a Map, and is useful for grouping using // an object key. const odd = { odd: true }; const even = { even: true }; array.groupByToMap((num, index, array) => { return num % 2 === 0 ? even: odd; }); // => Map { { odd: true}: [1, 3, 5], { even: true}: [2, 4] }