Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter and calculate the properties of objects from the same table using javascript

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading