I am new in NodeJS and I am learning on how to calculate the data,
Consider the JSON data from the url is like this and there are about 100 data.
[{
"ID": "01",
"sales": 11,
"points": 5,
"date": "2019-04-23T18:25:43.511Z"
},
{
"ID": "02",
"sales": 25,
"points": 15,
"date": "2022-05-23T18:25:43.511Z"
},
.
.
.
{
"ID": "12",
"sales": 20,
"points": 11,
"date": "2022-05-23T18:25:43.511Z"
},
{
"ID": "01",
"sales": 50,
"points": 30,
"date": "2023-11-23T18:25:43.511Z",
},
{
"ID": "01",
"sales": 40,
"points": 30,
"date": "2021-07-23T18:25:43.511Z",
}]
I want to count how many sales each ID made in between starting date beginning 2021 January until end date December 2023. The result would be somehow like this
[{
"ID": "01",
"totalsales": 150
},
.
.
.
{
"ID": "15",
"totalsales": 300
}]
3
Answers
You can do it pretty easily with the help of with the
reduce
function:You can use
Array.reduce()
to group the items byID
.This creates an object with a property for each ID, we can then use
Object.values()
to get the result as an array.We’ll also filter by date, checking that each date is between the start and end dates.
You can easily do it like this: