如何在 JavaScript 中不使用 reduce() 对数组进行分组

Front-end developers frequently transform arrays: filtering, mapping, reducing. And sometimes grouping. Grouping used to require custom reduce() logic, which often felt like more boilerplate than it was worth.

前端开发者经常对数组进行转换:过滤、映射、归约,有时还要分组。过去分组需要自定义 reduce() 逻辑,常常让人觉得样板代码比实际价值还多。

But that’s changing. JavaScript now has native support for grouping data with Object.groupBy() and Map.groupBy(). These static methods make grouping expressive, concise, and far more readable, without the need for external libraries or complex reduce() patterns.

但情况正在改变。JavaScript 现已原生支持用 Object.groupBy()Map.groupBy() 对数据进行分组。这些静态方法让分组表达清晰、简洁且更易读,无需外部库或复杂的 reduce() 模式。

What are Object.groupBy() and Map.groupBy()?

什么是 Object.groupBy()Map.groupBy()

Both of these methods were introduced in ES2024 and allow you to group elements of an array by a key generated from a callback function.

这两个方法都在 ES2024 中引入,允许你通过回调函数生成的键对数组元素进行分组。

Object.groupBy(array, callback)

Object.groupBy(array, callback)

This method returns a plain JavaScript object. The keys are strings derived from your callback, and the values are arrays of elements that match each key.

该方法返回一个普通 JavaScript 对象。键是由你的回调生成的字符串,值是与每个键匹配的元素数组。

Map.groupBy(array, callback)

Map.groupBy(array, callback)

This method returns a Map, which allows for non-string keys and maintains insertion order.

该方法返回一个 Map,允许使用非字符串键并保持插入顺序

Quick examples

快速示例

Object.groupBy()

Object.groupBy()

const items = ['apple', 'banana', 'orange', 'blueberry']; const grouped = Object.groupBy(items, item => item[0]); console.log(grouped);





The callback returns the first letter of each fruit, grouping them accordingly.

回调返回每个水果的首字母,并据此进行分组。

Map.groupBy()

Map.groupBy()

const items = [1.1, 2.3, 2.4, 3.5]; const grouped = Map.groupBy(items, Math.floor); console.log(grouped);





Because Map.groupBy() can use non-string keys (like numbers or objects), it’s more flexible in certain scenarios.

由于 Map.groupBy() 可以使用非字符串键(如数字或对象),在某些场景下更加灵活。

Replacing reduce() with groupBy()

groupBy() 替换 reduce()

Before groupBy(), grouping requ...

开通本站会员,查看完整译文。

- 위키
Copyright © 2011-2025 iteam. Current version is 2.146.0. UTC+08:00, 2025-10-22 21:39
浙ICP备14020137号-1 $방문자$