gpt4 book ai didi

javascript - 按卖家对一系列销售额进行分组,从每个卖家那里获取总数,按总销售额排序

转载 作者:行者123 更新时间:2023-12-02 01:39:30 25 4
gpt4 key购买 nike

我有一个这样的数组:

[
{
"orderId": 1,
"orderDate": "2021-04-28T08:20:58Z",
"status": "Confirmed",
"sellerName": "Chris Gilmour",
"revenue": 2316.49
},
{
"orderId": 2,
"orderDate": "2020-12-19T12:30:18Z",
"status": "Confirmed",
"sellerName": "Alanna Sumner",
"revenue": 2928.88
},
{
"orderId": 4,
"orderDate": "2020-12-24T08:00:09Z",
"status": "Confirmed",
"sellerName": "Beth North",
"revenue": 1550.19
},
{
"orderId": 5,
"orderDate": "2021-06-06T04:40:48Z",
"status": "Confirmed",
"sellerName": "Laura Ponce",
"revenue": 35.5
},
{
"orderId": 8,
"orderDate": "2021-08-27T05:13:40Z",
"status": "Canceled",
"sellerName": "Blade Newman",
"revenue": 2957.29
},
{
"orderId": 9,
"orderDate": "2020-12-26T08:07:57Z",
"status": "Confirmed",
"sellerName": "Alanna Sumner",
"revenue": 2164.75
},
{
"orderId": 10,
"orderDate": "2021-04-23T18:44:19Z",
"status": "Confirmed",
"sellerName": "Blade Newman",
"revenue": 2287.55
}
]

我希望新数组是:

[ 
{
"sellerName": "Blade Newman",
"totalRevenue": 5244.84
},
{
"sellerName": "Alanna Sumner",
"totalRevenue": 5093.63
},
{
"sellerName": "Chris Gilmour",
"totalRevenue" : 2316.49
},
{
"sellerName": "Beth North",
"totalRevenue": 1550.19
}

]

所以我希望数组按 sellerName 分组,销售量汇总并由总销售额最高的卖家订购。

我试图通过使用 forEachs 和 reduces 来解决这个问题,但我失败了,如果有人能帮助我,那就太好了。

提前致谢。

最佳答案

正如@CarySwoveland在评论中描述的那样,您可以将每个卖家的收入累加到一个对象中,将对象条目转换为数组进行排序,然后根据排序后的值生成一个新对象:

const sales = [{
"orderId": 1,
"orderDate": "2021-04-28T08:20:58Z",
"status": "Confirmed",
"sellerName": "Chris Gilmour",
"revenue": 2316.49
},
{
"orderId": 2,
"orderDate": "2020-12-19T12:30:18Z",
"status": "Confirmed",
"sellerName": "Alanna Sumner",
"revenue": 2928.88
},
{
"orderId": 4,
"orderDate": "2020-12-24T08:00:09Z",
"status": "Confirmed",
"sellerName": "Beth North",
"revenue": 1550.19
},
{
"orderId": 5,
"orderDate": "2021-06-06T04:40:48Z",
"status": "Confirmed",
"sellerName": "Laura Ponce",
"revenue": 35.5
},
{
"orderId": 8,
"orderDate": "2021-08-27T05:13:40Z",
"status": "Canceled",
"sellerName": "Blade Newman",
"revenue": 2957.29
},
{
"orderId": 9,
"orderDate": "2020-12-26T08:07:57Z",
"status": "Confirmed",
"sellerName": "Alanna Sumner",
"revenue": 2164.75
},
{
"orderId": 10,
"orderDate": "2021-04-23T18:44:19Z",
"status": "Confirmed",
"sellerName": "Blade Newman",
"revenue": 2287.55
}
];

let totalsales = sales.reduce((acc, {
sellerName,
revenue
}) => {
acc[sellerName] = (acc[sellerName] || 0) + revenue;
return acc;
}, {});

totalsales = Object.entries(totalsales)
.sort((a, b) => b[1] - a[1])
.map((v) => ({ sellerName: v[0], totalRevenue: v[1] }))

console.log(totalsales)

关于javascript - 按卖家对一系列销售额进行分组,从每个卖家那里获取总数,按总销售额排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71850556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com