输出给定日期范围内每个网站Id的聊天和错过聊天的总和



我有以下数组:-

[{
"websiteId": "4f8b36d00000000000000001",
"date": "2019-04-01T00:00:00.000Z",
"chats": 121,
"missedChats": 0
},
{
"websiteId": "4f8b36d00000000000000002",
"date": "2019-04-01T00:00:00.000Z",
"chats": 13,
"missedChats": 0
},
{
"websiteId": "4f8b36d00000000000000001",
"date": "2019-04-02T00:00:00.000Z",
"chats": 92,
"missedChats": 1
}]        

响应应为:

a( 如果未提供日期范围,则应计算整个数据集的总和。

[{
"websiteId": "4f8b36d00000000000000001",
"chats": 121+92,
"missedChats": 0+1
},
{
"websiteId": "4f8b36d00000000000000002",
"chats": 13,
"missedChats": 0
},
]

b( 如果日期范围newDate(2019,3.1(new Date(2019/2.1(

[{
"websiteId": "4f8b36d00000000000000001",
"chats": 121+92,
"missedChats": 0+1
},
{
"websiteId": "4f8b36d00000000000000002",
"chats": 13,
"missedChats": 0
},
]
Use reduce to sum the values, the below code may help you.

let data = [
{
websiteId: '4f8b36d00000000000000001',
date: '2019-04-01T00:00:00.000Z',
chats: 121,
missedChats: 0,
},
{
websiteId: '4f8b36d00000000000000002',
date: '2019-04-01T00:00:00.000Z',
chats: 13,
missedChats: 0,
},
{
websiteId: '4f8b36d00000000000000001',
date: '2019-04-02T00:00:00.000Z',
chats: 92,
missedChats: 1,
},
];
let result = data
.map(item => item.websiteId)
.filter((item, index, self) => self.indexOf(item) === index)
.map(websiteId =>
data
.filter(_item => _item.websiteId === websiteId)
.reduce(
(r, c) => {
r.chats += c.chats;
r.missedChats += c.missedChats;
r.websiteId = c.websiteId;
return r;
},
{chats: 0, missedChats: 0},
),
);
console.log(result);

最新更新