What is the best way to find the average within different groups in a JavaScript Array?

I am currently working with the Angular JS framework and have a NodeJS array like this:

var arr = [{"object":"Anguille","fct":"Type A","value":"2"},{"object":"Athérine","fct":"Type A","value":"1.0031643586595139"}, {"object":"Epinoche","fct":"Type B","value":"1"}, {"object":"Mulet ","fct":"Type B","value":"5"}];

I am trying to calculate the mean of the "value" grouped by each "fct" as follows:

{ 'Type A': 1.5, 'Type B': 3 }

So far, I have managed to group the values but only using sum and not mean. I believe I need to use the arr.reduce function but I am unsure about how to implement it in my code.

This is the snippet I have tried:

const obj = {};
arr.forEach((item) => {
  obj[item.fct] = obj[item.fct] ? obj[item.fct] + 
  parseInt(item.value) : parseInt(item.value);
});

console.log(obj);

I seem to be stuck at this point. Can you suggest a way to modify my snippet to calculate the mean instead of the sum?
Any guidance or help on this would be highly appreciated. Thank you.

Answer №1

It's possible to extract the totals and counts from each group, then construct the average for the final output.

const
    data = [{ object: "Anguille", fct: "Type A", value: "2" }, { object: "Athérine", fct: "Type A", value: "1.0031643586595139" }, { object: "Epinoche", fct: "Type B", value: "1" }, { object: "Mulet", fct: "Type B", value: "5" }],
    grouped = data.reduce((r, { fct, value }) => {
        r[fct] ??= { total: 0, count: 0 };
        r[fct].total += +value;
        r[fct].count++;
        return r;
    }, {}),
    result = Object.fromEntries(Object
        .entries(grouped)
        .map(([key, { total, count }]) => [key, total / count])
    );

console.log(result);

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

I couldn't identify the Material import within the child modules of Angular 2

I am facing an issue with importing custom material.ts modules in my app.module.ts file. I am unable to use Material in components declared at the module root level. However, when I create a child module (ClientModule) and declare a component there, Materi ...

Identify instances of repeated values in input fields

I'm working on a complex html form that includes multiple email fields. To ensure data integrity, I want to prevent users from entering the same email in more than one field. After some trial and error, I successfully identified duplicate emails by s ...

Pressing on an HTML element using JavaScript via the Selenium driver does not trigger the action

I'm attempting to use Selenium with Python to click on an element using JavaScript. Here's a snippet of my code: driver.execute_script("els=document.getElementsByClassName('buttons');\ for (var i = 0; i < els.length; i++) { ...

Sign up to receive updates on PageSize and PageIndex settings for MatTable in Angular Material

Currently, I am incorporating an angular material Table and paginator into my project. The challenge I am facing is how to send the pageSize and pageIndex values to the backend in order to handle paging on that side. Our application deals with a large am ...

Creating secure paths with ReactJS

I'm currently working on implementing protected routes in my React application. I have a Node.js backend with an endpoint called /isLoggedIn that checks if the user is logged in. The backend functionality is working fine, but I'm encountering mul ...

How can you create a sophisticated JavaScript object with an intricate design?

In my code, I frequently instantiate an object with the following structure: costs: { totalPerYear, totalEver, perMonth: { items: { depreciation, insurance, credit, inspection, ...

Unable to locate the next/google/font module in my Typescript project

Issue With Import Syntax for Font Types The documentation here provides an example: import { <font-name> } from 'next/google/font'; This code compiles successfully, but throws a "module not found" error at runtime. However, in this disc ...

Is it achievable to obtain the parameters in $http within Angular framework?

Looking for a solution I currently have this code snippet: let promise = $http.get('/api/users'); Is there a way to extract the parameters from the promise object? Here is what I envision: let promise = $http.get('/api/users'); let ...

Retrieve the selected option value from a dropdown menu when hovering or making a change within the same event

Apologies for my poor English. Is there a way to retrieve the value of a select box when a user either changes the select box or hovers over it with just one event? I attempted the following code snippet but it did not work as expected: jQuery("select[nam ...

Encountering a problem with AngularJS - receiving the [ng:areq] error, for more information visit http://errors.angularjs.org/1.3.2/ng/areq

While working on my CRUD angularApp, I encountered a strange error in Chrome dev tools. Here is the complete error message: error: [ng:areq] http://errors.angularjs.org/1.3.2/ng/areq?p0=DbController&p1=not%20a%20function%2C%20got%20string at angular.j ...

Chrome Developer Tools - Array Length Discrepancies

While exploring Chrome DevTools, I came across an inconsistency that caught my attention. The screenshot above shows the issue I encountered. Initially, it indicated that the object contained a Body and a Head, with the head being an array of length 1. Ho ...

Creating table structure dynamically using Node.js

I'm attempting to automatically create a table using nodejs "@google-cloud/bigquery": "^3.0.0" with the following approach: const bigqueryClient = new BigQuery(); schema = `driverId:string, passengerIds:(repeated string), pickedUp:(repeated s ...

What is the best way to update the color of a v-select component?

https://i.sstatic.net/6VOIo.png Currently utilizing Vuetify for my project <v-select id="makeMeBlue" dense outlined :items="form.values.urlTypes" label="Single or Multi URL" v-model="form.values.urlType" ...

JSON format is used for returning values from WebMethod calls

How can I retrieve values from a Webmethod and format them in JSON for the client? I have two static int values that need to be returned. Do I have to create a new object with these properties each time, or is there a more efficient way to handle this? Th ...

Dealing with Asynchronous JavaScript code in a while loop: Tips and techniques

While attempting to retrieve information from an API using $.getJSON(), I encountered a challenge. The maximum number of results per call is limited to 50, and the API provides a nextPageToken for accessing additional pages. In the code snippet below, my i ...

Angular 2 Observables consistently deliver undefined results

I keep encountering an issue where I am always receiving 'undefined' in my component code. Any assistance on this matter would be greatly appreciated. When I attempt to write to the console, it consistently returns 'undefined'. I am c ...

Trouble with loading TypeScript Express REST API routes!

I've been working on accessing data from my custom REST API, but I'm encountering an issue where the JSON data is not being displayed when I navigate to the endpoints. I have set up server, controller, and data controller classes in order to crea ...

WebStorm Angular 13 async pipe issue: Missing import statement

Recently, I updated to Angular 13 and noticed that in my WebStorm, the async pipe is now showing up as red with an error message saying: Missing require() statement https://i.stack.imgur.com/qNRui.png In addition, all directives are displaying a warnin ...

Tips for Repurposing a React Table

I am in the process of developing my own react component library to be used across my entire application. At the moment, I have started with a table component which is currently undergoing testing. However, I am facing the challenge of calling the componen ...

Setting up Scss and purgeCss configuration in Next.js custom postCSS configuration: A step-by-step guide

My current project is using Scss in combination with Bootstrap for design. I have implemented purgeCss to remove unused Css, and customized my postcss.config.js file as follows: module.exports = { plugins: [ "postcss-flexbugs-fixes", [ " ...