Steps for calculating the average of several columns within a table using Angular 10

Currently, I have a function that successfully calculates the sum of JSON data in all columns on my tables. However, my attempt to get the average of each column is resulting in NaN or infinity. What could be the issue here?

Here is my current implementation for obtaining the sum:

getSum(columnNumber) {
    let sum = 0;
    const columnNumberToPropertyMap = [
      "id",
      "teamNumber",
      "rural",
      "completed",
      "entirehouseholdabsent",
      "postponed",
      "refused",
      "vacant",
      "dwelling"     
    ];
    const property = columnNumberToPropertyMap[columnNumber];
    return this.rural.reduce((acc, curr) => {
      const adder = isNaN(Number(curr[property])) ? 0 : Number(curr[property]);
      sum = acc + adder
      return sum;
    }, 0).toFixed(2);
  }

This code successfully gives me the sum of all the rows in the column.

Now, here is how I'm attempting to find the average of each column:

 getSum(columnNumber) {
        let sum = 0;
        let average = 0;

        const columnNumberToPropertyMap = [
          "id",
          "teamNumber",
          "rural",
          "completed",
          "entirehouseholdabsent",
          "postponed",
          "refused",
          "vacant",
          "dwelling"     
        ];
        const property = columnNumberToPropertyMap[columnNumber];
        return this.rural.reduce((acc, curr) => {
          const adder = isNaN(Number(curr[property])) ? 0 : Number(curr[property]);
          sum = acc + adder
          average = (sum) / adder;
          return average;
        }, 0).toFixed(2);
      }

Unfortunately, I keep encountering NaN or infinity at the bottom of each column. The formula I am using is 'average = total of each column / no of items on each column'.

Answer №1

If you want to calculate the average, you can simply use the getSum function and then divide by the total number of rows. Here is how you can implement it:

calculateAverage(columnNumber) {
    let sum = getSum(columnNumber);
    let count = this.urban.length;
    return sum / count;
}

Alternatively, you can calculate the average in a single line like this:

return getSum(columnNumber) / this.urban.length;

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

Uh oh! An issue occurred: Cannot access values of an undefined property (reading 'valueOf')

I am attempting to loop through the JSON data and extract the start time and end time keys. I have tried two different methods in my API code to achieve this. The console.log is not showing any errors, but the other loop method is causing an error to appea ...

Learn the proper way to specify the return type of a function as a class, rather than an instance, in Typescript

Is there a way to declare that a function returns a generic class definition? I have tried the following for non-generic classes, but it does not work for generic ones: export function composeAll(composeFunction: Function, depsFunction: Function): (compon ...

Angular project models

I'm exploring the Core/Shared/Feature design pattern for building large, scalable applications in Angular, and I find myself unsure about where models fit in. Is there a consensus on which module they belong in? I came across a post suggesting that ...

Using a snippet of HTML code from one Angular component in another component

Is it possible to use a specific div element from one Angular component in another component? main component.html <html> <div1> some elements </div1> <div2> some elements </div2> In the child ...

Is it possible to utilize jwt tokens together with Firebase authentication?

Having previously built Spring Boot applications utilizing jwt tokens, Angular 7, and MySQL, I am now considering transitioning to Firebase solely for authentication purposes. Some tutorials suggest that Firebase can be directly implemented through Angular ...

typescript decorator implemented on a class that is nested within another class

Is it possible to decorate a nested property within a class? Let's explore with an example: function log(name: string = 'DecoratedProp') { return function logHandler(target: any, field: any) { // get the key ...

"ENUM value is stored in the event target value's handle property

My issue lies with the event.target.value that returns a 'String' value, and I want it to be recognized as an ENUM type. Here is my current code: export enum Permissions { OnlyMe, Everyone, SelectedPerson } ... <FormControl> & ...

Tips for looping through an array of objects in Angular 9 and adjusting the time if the <mat-checkbox> is selected

I am currently working with an array of objects that are displayed in a <mat-table>. Each object has a property called sync, which is represented by a <mat-checkbox>. My goal is to create functionality where checking the box and then pressing ...

Changing the default component prefix in Angular to prevent TSLint warnings

When I create a new Angular 2 app with Angular CLI, the default component prefix is set to app-root for the AppComponent. However, if I decide to change the selector to something different like "abc-root", @Component({ selector: 'abc-root', ...

I am trying to figure out how to retrieve the name of the property that is bound to [(ngModel)] in Angular 6

Here is a custom component example: <form-text [(ngModel)]="dataItem.prop1"> </form-text> Is there a way to extract the property name "prop1" from the class in this scenario? @Component({ selector: 'form-text', template ...

Generating typescript definitions for Polymer 2.4 packages

According to information provided in the latest announcement, declarations are now automatically generated from the Polymer source. I recently upgraded to Polymer 2.4 and encountered an error during project build due to a missing typescript definition fil ...

typescript is reporting that the variable has not been defined

interface User { id: number; name?: string; nickname?: string; } interface Info { id: number; city?: string; } type SuperUser = User & Info; let su: SuperUser; su.id = 1; console.log(su); I experimented with intersection types ...

Issue: UNSUPPORTED: The keyword "id" is not supported, please use "$id" for the schema ID after upgrading to Angular13

After upgrading from Angular 12 to Angular 13, I encountered an error while running my e2e tests. How can I go about identifying the root cause of this issue? I am able to compile with 'ng build'. /opt/wdio/node_modules/@angular-devkit/core/nod ...

Obtaining Data from a Database Using Angular

I have developed a front-end website using Angular as my framework, integrated with node.js. To interact with the database, I created a "server.ts" file and connected it successfully to my DB. Now, my goal is to fetch data from the database and display i ...

Animating the Click Event to Change Grid Layout in React

Can a grid layout change be animated on click in React? For instance, consider the following component: import { Box, Button, styled, useMediaQuery } from "@mui/material"; import Row1 from "./Row1"; import React from "react"; ...

"Error TS2339: The property specified does not exist within type definition", located on the input field

When a user clicks a specific button, I need an input field to be focused with its text value selected entirely to allow users to replace the entire value while typing. This is the markup for the input field: <input type="text" id="descriptionField" c ...

Strange compilation error encountered with ng-packagr due to Angular @Input inheritance

Encountering a perplexing error message in Angular 7 while working with @Input inheritance. The error message seems illogical because I have 1 mandatory @Input and 2 optional @Input, so things should align... Error: Directive MyComponent, Expected 2 argum ...

What is the best way to send various parameters to a component using [routerLink] or router.navigate?

My app-routing.module.ts is configured as shown below: const routes: Routes = [ { path: "branches/:branch", component: BranchesComponent }, // ... ]; In addition, in my app.component.html, I have the following code: <li> ...

Improving DynamoDb Query Results with Type Hinting

In the following Typescript code, how can I specify which fields should be present in my Query Items Result? const request: DynamoDB.DocumentClient.QueryInput = { TableName: UnsubscriptionTokensRepository.TABLE_NAME, IndexName: 'TokenIndex&ap ...

Following an Angular update, the npm installation process encounters issues due to conflicts related to peer dependencies

I am facing challenges with updating my Angular version. When I try to use the command ng update, the output I receive is as follows: Name Version Command to update ------------------------------ ...