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

Is there a glitch in the three.js loadOBJMTL loader?

Encountering an issue with the OBJMTL loader in three.js. I'm working with obj/mtl/jpeg files and getting load errors that look like this: "THREE.OBJMTLLoader: Unhandled line 4033/5601/6659" OBJMTLLoader.js:347 Seems like there is a problem with a c ...

The KeyboardAvoidingView disrupts the structure of the flexbox layout

Check out this code snippet: return ( <KeyboardAvoidingView style={{ flex: 1 }} behavior="padding" enabled> <View style={style.flex1}> <View style={style.imageContainer}> <Image style={style.image} ...

When clicking on the material-ui autocomplete feature in a React JS application, a blank page unexpectedly opens

I am encountering a problem where, upon clicking the Autocomplete component imported from material-ui, it displays a blank page. const defaultProps = { options: catalogs, getOptionLabel: (option) => option.catalogsLink, }; <Autocomplet ...

All API endpoints must be accessed with a jwt token

After diving into the nextjs documentation, I stumbled upon something interesting. import { getToken } from "next-auth/jwt" const secret = process.env.NEXTAUTH_SECRET export default async function handler(req, res) { // if using `NEXTAUTH_SEC ...

Tips for switching a group of buttons within a userscript by clicking a single button?

Apologies if my wording is not clear, allow me to clarify. I am in the process of developing a userscript that will display a set of buttons below a main button when clicked. These additional buttons will serve different functions and should disappear whe ...

A common occurrence is for jQuery/Javascript Ajax POST to generate 6 identical posts when used within a .each loop, happening approximately 20

Context: Building a jQuery mobile phonegap application with multipage-ajaxload and sisyphus enabled form that utilizes an AJAX POST loop to interact with a GUI database. The process involves posting 171 section entries, along with one summary entry to a se ...

transferring information from Node.js/MongoDB to the front-end (invisible in the browser)

I am trying to retrieve data from a mongodb database and pass it to the front-end. The function I have written works in the console, where I can see an array containing elements. However, when I try to view it in the browser, it shows undefined. I am worki ...

Converting Python dictionary to JSON format

As I am still new to Python programming, please excuse any mistakes I may make I'm attempting to create a json file using 2 dictionaries and write the output to the file with the code provided below on Windows import json import sys import string f ...

Exploring the Power of NPM Modules in an Electron Renderer

Having trouble accessing lodash in an electron renderer. I'm a beginner with Electron and know that both the main process and renderer (local html file) have access to node. I can require something from node core like fs and it works fine, but when I ...

Creating a loop in a column-based carousel without using JavaScript

I'm currently working on developing a carousel using JavaScript or jQuery. I've attempted the code snippet below, but I'm having trouble getting it to display in 3 or 4 columns. While I understand that Bootstrap can handle this easily, I&apo ...

Ways to retrieve the text of the chosen radio button label with the help of jQuery

There is a radio button on my webpage that looks like this: <div id="someId"> <label class="radio-inline"> <input name="x" type="radio" onchange="GetSelectedVal();">Yes</label> <label class="radio-inline"> ...

The integration of Angular and Node API within the IISNode directory structure is experiencing functionality issues

Read more about the question I have successfully set up my Node API and Angular component with IISnode. However, when accessing the application from the IIS server, I noticed that they are showing in different directories (see image below). Additionally, I ...

There seems to be a glitch preventing the Redis client from properly executing

Having some trouble with my Redis implementation in Node.js. Despite using async/await as recommended in the docs, I'm only seeing 'console log 1' being logged. Any ideas on what might be causing this issue? Any help or suggestions would be ...

What purpose does the symbol '$' serve in React component properties?

While delving into the world of styled-component, I encountered some difficulties with the 'adapting based on props' aspect. import './App.css'; import styled from 'styled-components' const PrimaryButton = styled.button` co ...

Why is the jQuery Ajax AutoComplete feature not functioning properly?

Hey there, I'm currently utilizing CodeIgniter along with Ajax AutoComplete for jQuery in my project. When setting up my autocomplete feature in jQuery, I used the following code: a = $('.city').autocomplete({ serviceUrl: "<? echo $ ...

Is there a way to customize the styles for the material UI alert component?

My journey with Typescript is relatively new, and I've recently built a snackbar component using React Context. However, when attempting to set the Alert severity, I encountered this error: "Type 'string' is not assignable to type 'Colo ...

Trouble encountered when transmitting JavaScript array through AJAX to Laravel

I am encountering an issue with sending a JavaScript array to a controller via an AJAX GET method. Here is the structure of my JavaScript: var requestData = JSON.stringify(commentsArray); console.log(requestData); //I can see the correct JSO ...

Creating a function that writes to a file by utilizing the data input from

After running the provided code snippet, it successfully works in a standalone project. However, I am interested in making modifications to replace the variable "sample_text" with an output that is displayed in the terminal instead of being hardcoded int ...

Activate the places_changed event in Google Maps by clicking the submit button

I would like to activate my placed_changed function when a submit button is clicked. Here's what I have so far: I've set up a searchbox using google.maps.places.SearchBox, and when I press enter while the search box is in focus, it triggers the e ...

Challenges with rendering items in a FlatList component in React Native

I'm currently working on transferring data from a data.json file to video.js <Image source={{ uri: video.snippet.thumbnails.medium.url }} style={{ height: 200 }} /> and I want this file to be rendered in a flatlist <FlatList showsHorizo ...