I hope my question is not asked too much in SO.
I have an array of 3 objects such as: :
const objStart1 = {
'user': 1,
'score': 15,
'date': 'Monday'
}
const objStart2 = {
'user': 1,
'score': 7,
'date': 'Friday'
}
const objStart3 = {
'user': 2,
'score': 5,
'date': 'Monday'
}
I would like to group by date then calcul the average of the score by day (and delete user) and return a new array of objects like :
const objStart1 = {
'average': 10,
'date': 'Monday'
}
const objStart2 = {
'average': 7,
'date': 'Friday'
}
It seems, we can use filter + reduce but my results are pathetic… Is there a good solution?
thank you in advance.
>Solution :
This should do the trick.
I put your items into an actual array, and I replaced Date with date.
const input = [
{
'user': 1,
'score': 15,
'date': 'Monday'
},
{
'user': 1,
'score': 7,
'date': 'Friday'
},
{
'user': 2,
'score': 5,
'date': 'Monday'
},
]
const sumList = input.reduce((acc, current) => {
if(!acc.find(obj => obj.date === current.date)) acc.push({date: current.date, sum: 0, count: 0})
const currCounter = acc.find(obj => obj.date === current.date)
currCounter.sum += current.score
currCounter.count++
return acc
}, [])
.map(({date, sum, count}) => ({ date, average: sum/count }))
console.log(sumList)