Reputation: 861
Suppose I have an array of object as:
const ReadingTime = [
{
"user": "john",
"readingPeriod": 8681
},
{
"user": "john",
"readingPeriod": 8867
},
{
"user": "naresh",
"readingPeriod": 22321
},
{
"user": "Samul",
"readingPeriod": 1212
},
{
"user": "Samul",
"readingPeriod": 1221
}
]
I want to calculate average time for each user and generate the output as:
{"john":8774,"naresh":22321,"Samuel":121.6}
I tried doing as:
let avgReadingTime = ReadingTime.filter(RT => RT.user == "john")
.map(el => ({ "processingTime": el.readingPeriod }));
and it gives reading for user john only, as [8681,8867].
But this is a really long process, I want to calculate for dynamic user, user adds dynamically and we can have average reading time for each user.
Please do let me know if anyone needs any further details. I'm still trying to figure out, will update my question according if something comes up.
**Edit: Previously my accepted answer is incorrect. As the solution provided not giving an average. Sorry for accepting without being thorough.
Upvotes: 0
Views: 65
Reputation: 25408
You could use the reduce method of an array.
const ReadingTime = [
{
user: "john",
readingPeriod: 8681,
},
{
user: "john",
readingPeriod: 8867,
},
{
user: "naresh",
readingPeriod: 22321,
},
{
user: "Samul",
readingPeriod: 1212,
},
{
user: "Samul",
readingPeriod: 1221,
},
];
const result = ReadingTime.reduce((acc, curr) => {
const { user, readingPeriod } = curr;
acc[user] = acc[user] ? (acc[user] + readingPeriod) / 2 : readingPeriod;
return acc;
}, {});
console.log(result);
Upvotes: 1
Reputation: 6276
You can always use Array.prototype.reduce()
ReadingTime.reduce((prev, curr) => {
if (prev[curr.user]) {
return {
...prev,
[curr.user]: (prev[curr.user] + curr.readingPeriod) / 2,
};
}
return {
...prev,
[curr.user]: curr.readingPeriod,
};
}, {});
Upvotes: 0