What is the best method to determine the mean score by utilizing the ID values obtained from API responses?

These are the responses retrieved from the API:

const attractions = [
  {"id": 1,"name": "drive on avenue"},
  {"id": 2, "name": "diving"},
  {"id": 3,"name": "visiting mangroove"},
];

const reviews = [
  {"id": 1,"score": 1.5},
  {"id": 2, "score": 2} ,
  {"id": 3,"score": 5.5},
  {"id": 3,"score": 4},
  {"id": 2,"score": 3},
  {"id": 1,"score": 3.5},
  {"id": 3,"score": 5},
  {"id": 2,"score": 4}
]

The anticipated result should be as follows:

[{"name": "drive on avenue", "score": 2.5},
{"name": "diving", "score": 3},
{"name": "visiting mangroove", "score": 4.83}
]

I attempted to utilize reduce, however, it summed up all scores together. How can I compute the average score for each ID?

Answer №1

Iterate over the attractions array and calculate the average review score for each attraction using the reviews array. Here is an example:

const attractions = [
    {"id": 1,"name": "drive on avenue"},
    {"id": 2, "name": "diving"},
    {"id": 3,"name": "visiting mangroove"},
  ];
  
  const reviews = [
    {"id": 1,"score": 1.5},
    {"id": 2, "score": 2} ,
    {"id": 3,"score": 5.5},
    {"id": 3,"score": 4},
    {"id": 2,"score": 3},
    {"id": 1,"score": 3.5},
    {"id": 3,"score": 5},
    {"id": 2,"score": 4}
  ]

var returned = []
attractions.forEach((attraction) => {
    let arr = reviews.filter(x => x.id == attraction.id).map(x => x.score);
    let score = arr.reduce((a, b) => a + b, 0)/arr.length;
    returned.push({ name: attraction.name, score: score});
})

console.log(returned);

map and filter functions are utilized in this code snippet.

Map

Filter

To summarize, map extracts values from objects like {id: 1, score: 3} => 3. While filter is used to select specific ids from the reviews.

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

List of Nodes with five links

I'm encountering an issue when trying to reference the final node. The expected output is: Linked List with 5 nodes Node Value: Head Node / Next Node Value: Second Node / Last Node Value: null Node Value: Second Node / Next Node Value: Third N ...

Change the height of textarea dynamically using jQuery

I am trying to create a comment box similar to Facebook's, where it resizes as text fills it using Expanding Text Areas Made Elegant This is how my view looks: <div class='expandingArea'> <pre><span></span></ ...

Troubleshooting why jQuery Ajax post is not sending parameters

Struggling with jQuery's $.ajax() function to send form data to an MVC route. Despite passing data, all parameters end up null in the MVC action: jQuery: $(function () { $('#signupform').submit(function (e) { e.preventDefault() ...

"Custom object fails to deserialize properly using Json.NET, resulting in a null value

I'm struggling with converting a JSON string to a C# object using Json.NET. I utilized the AJAX call .ashx $.ajax({ url: "/Handler/Handler.ashx?WorkType=SaveData", type: "POST", data: JSON.stringify({ 'DataInfo': Info }), / ...

Decode my location and input the address before validating it

While I have come across numerous plugins that enable geolocation and display it on a map, I am searching for something unique. I am interested in implementing geocoding when a user visits the page with an option to "allow geolocation." If the user agrees ...

Applying a class to an element in VueJS is not functioning as expected

My goal is to assign the class .testcolor to the div element when testvalue is true, and apply no class when it's false. I encountered an issue where the getClass method does not get called when added to :class attribute, but works fine when called f ...

Unable to sign out user from the server side using Next.js and Supabase

Is there a way to log out a user on the server side using Supabase as the authentication provider? I initially thought that simply calling this function would work: export const getServerSideProps: GetServerSideProps = withPageAuth({ redirectTo: &apos ...

Encountering the issue of receiving an undefined value for a variable despite having previously defined it within

I’ve been working on implementing the Google Maps distance matrix API with the google-distance-matrix library. Here’s the code snippet I’m using: app.get("/users", (req, res) => { // console.log(req.query); // res.send(req.query); ...

Is there a way for me to adjust the image dimensions so that it doesn't surpass the width of its parent container?

When working with images, it can be tricky to set the original width while also ensuring it fits within a parent container. For example, if the parent container has a width of 1000px, you may want the image to have a max-width of 100%, but not exceed 1000p ...

Laravel Mix fails to recognize VueJs integration in Laravel

Having an issue setting up VueJs with laravel 5.7 and mix where it keeps saying VueJs is not detected. I've already executed the npm install command. Below is my welcome view: <!doctype html> <html lang="{{ str_replace('_', '- ...

In JavaScript, creating a new array of objects by comparing two arrays of nested objects and selecting only the ones with different values

I've been struggling to make this work correctly. I have two arrays containing nested objects, arr1 and arr2. let arr1 =[{ id: 1, rideS: [ { id: 12, station: { id: 23, street: "A ...

What is the proper way to utilize express.json() and set headers (res.setHeader) at the same time?

I'm currently working on a POST request and need to both view the body of the request and set some headers. Specifically, I want to enable communication from localhost to localhost by adding Access-Control-Allow-Origin: * as a header. This is what my ...

The password-protected HTML blog remains hidden until the correct entry is entered into the password box, causing

After successfully creating a password redirect page where entering the correct password redirects you to another URL (psswrdtest.tumblr.com with the password as correctpsswrd, redirecting to google.com*), I attempted to improve it by making the password p ...

Watch mp4 clips in various languages with ExpressJs

I have a question regarding streaming videos within my local network. My mp4 files contain multiple audio tracks in different languages. Is there a way to select a specific audio track to stream? For instance, could you specify a language as a query parame ...

What is the optimal method for transmitting both an image and JSON data to my express server?

Hey there! So I've set up a MongoDB database and I'm using Mongoose to work with it. Here's the model I have for my product: const productSchema = new Schema({ name: { type: String, required: true}, description: { type: String, required ...

turning every input field's border to red if none of them were filled out at least once

I struggle with javascript and need some help. I have a form with multiple input fields, and I want to ensure that the user fills in at least one of them. I found code that triggers an alert message if the user does not fill in any fields, but I would pref ...

React and Express are incompatible due to the error message "TypeError: undefined is not a function

I am attempting to display the data from this array on my website using react and express: [{"LocationName":"LIBERTY DOGS","Address":"105 Greenwood Ave N, Seattle WA","Available":"Y"},{"LocationName":"FREEDOM DOGS","Address":"105 Greenwood Ave N, Seattle ...

When attempting to evaluate JSON data on a specific computer, the function JSON

Something strange is happening and I can't seem to figure it out, causing a big issue for me. I am currently working on a .Net web application that utilizes JSON (not json2) along with other JS libraries. In one specific proxy, the function JSON.eval ...

Using jQuery and Perl to create a dynamic progress bar that is based on the current state of a "pipeline file" and utilizes AJAX

I'm looking to create a small pipeline that enables users to select a file and run multiple scripts using it as an input. Some of these scripts may take several minutes to complete (time depends on the file's size), so I want to display a progres ...

Storing multiple values of dynamically added elements in a single variable and accessing them within a function

Is it possible to store multiple values into a single variable and then access them in a setTimeout function? $(document).ready(function (){ div ({'div':'#noo','auto':'true','pos':'top',' ...