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

calculate 5 star ratings in js array of object

I have an array that consist of feedback objects. Each object is a user feedback left for a product:

Array [ {…}, {…} ]
0: Object { id: "1223", quality: 3, material: 4, … }
1: Object { id: "7342", quality: 3, material: 5, … }
...

Users can leave feedback for each category quality, material, … out of 5.

I want to use the weighted average so on my site, I can show for example:

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

quality: 3
material: 4

This is weighted average calculated by this formula:

quality: (5*0 + 4*0 + 3*2 + 2*0 + 1*0) / (2) = 3
material: (5*1 + 4*0 + 3*1 + 2*0 + 1*0) / (2) = 4

I want to add this my js project, so I loop through all feedback:

const total = []
const feedback = [{
    id: "1223",
    quality: 3,
    material: 4,
  },
  {
    id: "7342",
    quality: 3,
    material: 5,
  }
];
feedback.forEach(function(arrayItem) {
  const score = arrayItem.quality
  total.push(score)
})
console.log(total.reduce((partialSum, a) => partialSum + a, 0))

I am confused about how to do the calculation for each star, for example to get number of 1s, 2s, 3s, 4s, and 5 starts. How can I modify my code to return the rating result?

>Solution :

You could collect all sums in an object and calculate the aveage on the fly.

If you need an array, take only the values.

const
    feedback = [{ id: "1223", quality: 3, material: 4 }, { id: "7342", quality: 3, material: 5 }],
    types = ['quality', 'material'],
    result = feedback.reduce((r, o) => {
        types.forEach(type => {
            r[type] ??= { type, total: 0, count: 0 };
            r[type].total += o[type];
            r[type].avarage = r[type].total / ++r[type].count;
        });
        return r;
    }, {});

console.log(result);
console.log(Object.values(result));
.as-console-wrapper { max-height: 100% !important; top: 0; }
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