在某些浏览器的某些版本中,此方法被实现为 Array.prototype.group() 方法。由于 web 兼容性问题,它现在以静态方法实现。
函数功能
提供的回调函数返回的字符串值对给定可迭代对象中的元素进行分组。返回的对象具有每个组的单独属性,其中包含组中的元素的数组。
语法
items
为可迭代对象
cb
为函数接受当前迭代元素和索引,返回一个字符串,groupBy
函数将根据这个字符串进行分类
Object.groupBy(items, cb)
示例
const inventory = [{ name: "芦笋", type: "蔬菜", quantity: 5 },{ name: "香蕉", type: "水果", quantity: 0 },{ name: "山羊", type: "肉", quantity: 23 },{ name: "樱桃", type: "水果", quantity: 5 },{ name: "鱼", type: "肉", quantity: 22 },];const res = Object.groupBy(inventory, {type}=>type)console.dir(res)/*
Object
水果: (2) [{…}, {…}]
肉: (2) [{…}, {…}]
蔬菜: [{…}]*/