What is the process for determining the average rating of an array?

Here is an array of data provided:

    const ratingData = [
        {name: 'St. Marys School', rating:5},
        {name: 'St. Zaviers School', rating:4},
        {name: 'St. Marys School', rating:3},
        {name: 'Rahul English Medium School', rating:2},
        {name: 'St. Francis High School', rating:3},
        {name: 'Rahul English Medium School', rating:1},
        {name: 'St. Francis High School', rating:4},
        {name: 'Mother Marys High School', rating:5}
    ];

My goal is to calculate the average rating for each school in this array. The challenge lies in dealing with duplicate entries, such as having multiple ratings for a single school like "St. Mary's School". How can I combine these entries and calculate the average rating effectively? I attempted using the map function, but it did not provide the desired outcome.

The expected output should resemble the following: (This is just an example)

const output = [
     { name: 'St. Marys School', averageRating: 4},
     { name: 'St. Zaviers School', averageRating: 4},
     { name: 'Rahul English Medium School', averageRating: 1.5},
     { name: 'St. Francis High School', averageRating: 3.5},
     { name: 'Mother Marys High School', averageRating: 5}
];

Answer №1

const schoolRatings = [
    {name: 'Sunshine Elementary', rating:4},
    {name: 'Rainbow Middle School', rating:3},
    {name: 'Sunshine Elementary', rating:5},
    {name: 'Golden Oak High School', rating:2},
    {name: 'Evergreen Junior High', rating:3},
    {name: 'Golden Oak High School', rating:1},
    {name: 'Evergreen Junior High', rating:4},
    {name: 'Moonlight High', rating:5}
];

let sumRatingData = {};

for (let entry of schoolRatings) {
    if (sumRatingData[entry.name]) {
        sumRatingData[entry.name].total = sumRatingData[entry.name].total + entry.rating;
        sumRatingData[entry.name].count++;
    } else {
        sumRatingData[entry.name] = {
            total: entry.rating,
            count: 1
        };
    }
}

console.log('Total Ratings Data: ' + JSON.stringify(sumRatingData));

let averageRatings = [];

for (let entry of Object.keys(sumRatingData)) {
    averageRatings.push({
        name: entry,
        rating: sumRatingData[entry].total / sumRatingData[entry].count
    });
}

console.log('Average Ratings Data: ' + JSON.stringify(averageRatings));

The total ratings data will be:

{
    "Sunshine Elementary": {
        "total": 9,
        "count": 2
    },
    "Rainbow Middle School": {
        "total": 3,
        "count": 1
    },
    "Golden Oak High School": {
        "total": 3,
        "count": 2
    },
    "Evergreen Junior High": {
        "total": 7,
        "count": 2
    },
    "Moonlight High": {
        "total": 5,
        "count": 1
    }
}

And the average ratings data will be:

[
    {
        "name": "Sunshine Elementary",
        "rating": 4.5
    },
    {
        "name": "Rainbow Middle School",
        "rating": 3
    },
    {
        "name": "Golden Oak High School",
        "rating": 1.5
    },
    {
        "name": "Evergreen Junior High",
        "rating": 3.5
    },
    {
        "name": "Moonlight High",
        "rating": 5
    }
]

Answer №2

Illustrated below is a sample scenario utilizing the reduce() function together with a Map to identify duplicate entries.

The initial step involves reducing the original array into a Map that stores the ratings of repeated entries in an array format.

{
{'Sunset High School': [4, 3, 1]},
{'Riverside Academy': [5]},
...
}

Subsequently, we transform this populated Map back into an array using Array.from, and then calculate the average rating by reducing the array of ratings.

const ratingData = [
    {name: 'Sunset High School', rating:4},
    {name: 'Riverside Academy', rating:5},
    {name: 'Sunset High School', rating:3},
    {name: 'Lakeview Middle School', rating:2},
    {name: 'Brighton Junior High', rating:3},
    {name: 'Lakeview Middle School', rating:1},
    {name: 'Brighton Junior High', rating:4},
    {name: 'Green Valley Elementary', rating:5},
    {name: 'Sunset High School', rating:1}
    ]
    
const mapData = ratingData.reduce((acc, {name, rating}) => {
  const match = acc.get(name);
  match ? 
  match.push(rating) :
  acc.set(name, [rating]);
  return acc;
}, new Map);

const averageArray = Array.from(mapData, ([name, ratings]) => {
  const rating = ratings.reduce((a, r) => (a + r))/ratings.length;
  return { name, rating }
});

console.log(averageArray);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a PHP array containing strings and generate two-dimensional arrays as a result

One issue I encountered in PHP involves creating an array with a string while also cutting some images. Within my code, buildProject.php is included in index.php (with session_start(); for _session at the top). buildProject.php <?php $list_project = ...

Invoking a C# function inside a cshtml file

Having trouble calling a function in my CSHTML page. In the script of my CSHTML page : <script type="text/javascript" > //var sLoggedInUser = <%# GetSession_LoggedInIdUser() %>; $(document).ready(function () { ale ...

Once more, objects cannot be used as a child element in React

I understand that there are similar questions about this topic, but I am struggling to approach it in a different way. I really need an array of objects to be inside a map. I have created an array to map it, but I need to find different information to disp ...

WordPress: Issue with Dropdown onchange Event Not Triggering

I'm having trouble getting an event to fire when the dropdown value changes. Can anyone help me figure out where I might be going wrong? JavaScript code jQuery(document).ready(function($){ jQuery('#_ccounts select').on('change&apo ...

Modify the color of the object model when clicked - Three.js

When a user clicks on a specific part of the object model, I want to display the wireframe of that part to indicate which part is being modified. The user can then choose a color for that part from a palette. However, the line child.material.color.set(se ...

What is the best way to vanish the circles using keyboard commands?

After reviewing the example at http://bl.ocks.org/d3noob/10633704, my goal is to create an input field on my keyboard where I can enter a number, and then use array.slice() to make circles disappear based on that number. Unfortunately, my implementation ...

Having trouble importing Sequelize in Angular?

I'm encountering an issue in my app where I am unable to import the sequelize package. The error message reads: chunk {main} main.js, main.js.map (main) 2.02 kB [initial] [rendered] chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 691 b ...

Tips for concealing an input IP Address in React

Looking for suggestions on an IP Address mask input solution. The format might vary between 999.99.999.99 and 99.9.99.9, but react-input-mask does not support varying lengths. Any recommendations? ...

Avoid placing function declarations within blocks

My JavaScript code (shown below) is quite messy and has a persistent error that I can't seem to fix. The issue lies within the showPosition function, where I have nested a function within another function, which is not a recommended practice. I am rel ...

A guide on updating progress bar value based on user input

I have an input field and a progress bar that needs to be updated based on the input. The task is to input a number (%) and then display that value in the progress bar upon clicking the "Apply" button (btn-primary). Below is the HTML code provided: < ...

Utilizing AJAX within a Rails application to dynamically alter a database field without the need for a traditional form

I am facing a scenario where I have implemented a table with certain rows structured as follows: <div class="row chord-table-row" id= <%= "chord-#{chord.id}" %>> <div class="small-1 columns"><%= chord.id %></div> < ...

Having trouble running nodemon on my Windows 10 machine

Recently, I started diving into Node.js and managed to run my first node app successfully, albeit without using nodemon. To remedy this, I globally installed nodemon by running npm install -g nodemon, which went smoothly. However, upon executing nodemon in ...

What is the best way to create a universal root component in next.js for sending requests, no matter the page URL?

Currently, my goal is to send a request to the server whenever the page is refreshed or opened in a new tab. For instance, after hitting F5, I want to trigger a request. However, I do not want to make a request after every routing event. Essentially, upon ...

Can you explain the significance of the '#' symbol within the input tag?

I was reading an article about Angular 2 and came across a code snippet that uses <input type='text' #hobby>. This "#" symbol is being used to extract the value typed into the textbox without using ngModal. I am confused about what exactly ...

NG0303: Unable to establish a connection with 'ngbTooltip' as it is not recognized as a valid property of 'button'

ERROR: 'NG0303: Can't bind to 'ngbTooltip' since it isn't a known property of 'button'.' Encountering this issue in my Angular 12 project when running local tests, the ngbTooltip error is present in all .spec files. ...

Guide on incorporating text onto objects with three.js

I successfully incorporated text into my shirt model using a text geometry. Check out the code below: var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); ctx.font = 'italic 18px Arial'; ctx.te ...

Tips for implementing the JSON object table filter functionality

My website features a collection of json objects organized as shown below: [ { "a": true or false, "b": "information", "c": "information", "d": "information", "e": "information" }, ... ] The goal here ...

Can whitelist functionality be applied in the browser version of Babel?

While working on a project for my university, I wanted to utilize React. Since installation wasn't allowed, I had to resort to using the browser version of React. Everything was functioning well until I attempted to incorporate JSX into the browser. ...

In React JS, rendering occurs independently of API data retrieval

As a newcomer to ReactJS, I am in the process of creating a single registration page App that retrieves dropdown data from an API. However, I am encountering an error when attempting to fetch the data. Here is a snippet of my code: AppApi.js: var AppAct ...

Saving data inputted in a form using ReactJS and JavaScript for exporting later

What is the best way to save or export form input in a ReactJS/JS powered website? For example, if I have a form and want to save or export the data in a format like CSV after the user clicks Submit, what method should I use? Appreciate any advice. Thank ...