js原生超好用的数组分类方法Object.groupBy()

这是个新方法,版本高的浏览器才能用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script>
const inventory = [
{ name: "芦笋", type: "蔬菜", quantity: 5 },
{ name: "香蕉", type: "水果", quantity: 0 },
{ name: "山羊", type: "肉", quantity: 23 },
{ name: "樱桃", type: "水果", quantity: 5 },
{ name: "鱼", type: "肉", quantity: 22 },
];
console.log(inventory);


const result = Object.groupBy(inventory, ({ type }) =>{ return type });
console.log(result);

const demo = Object.groupBy(inventory, ({ quantity })=> {
return quantity > 5 ? "ok" : "restock";
});
console.log(demo);
</script>
</body>
</html>


js原生超好用的数组分类方法Object.groupBy()
https://github.com/chergn/chergn.github.io/7d392eeb2f16/
作者
全易
发布于
2024年3月28日
许可协议