Angular 4 - Sum all values within a nested array of a data model

I am working with an array of Models where each object contains another array of Models. My goal is to calculate the sum of all the number variables from the nested arrays using the code snippet below.

Model

TimesheetLogged.ts

export interface TimesheetLogged {
    ProjectId: string,   
    MondayHours: number,
    TuesdayHours: number,
    WednesdayHours: number,
    ThursdayHours: number,
    FridayHours: number,
    SaturdayHours: number,
    SundayHours: number   
}

Project.ts

import { TimesheetLogged } from "./TimesheetLogged";

export interface Project {
    ProjectId: number;  
    TimeLoggedHours: TimesheetLogged[];   
}

Piece of code from Component

public Projects: Project[];
//Get projects data from database and subscribe to Projects object  Successfully

let chartData: Array<number> = [];
    let mon:number= 0;
    let tue:number= 0;
    let wed:number= 0;
    let thu:number= 0;
    let fri:number= 0;
    let sat:number= 0;
    let sun:number= 0;

    this.Projects.forEach((empHours) => {
        empHours.TimeLoggedHours.forEach((hours) => {
            a => {
                mon += a.MondayHours;
                tue += a.TuesdayHours;
                wed += a.WednesdayHours;
                thu += a.ThursdayHours;
                fri += a.FridayHours;
                sat += a.SaturdayHours;
                sun += a.SundayHours;
            }  
        });            
    });
    chartData.push(mon);
    chartData.push(tue);
    chartData.push(wed);
    chartData.push(thu);
    chartData.push(fri);
    chartData.push(sat);
    chartData.push(sun); 

However I am getting Sum of all number variables as

[object Array][0, 0, 0, 0, 0, 0, 0]

Any update required in this code. Any other simpler solution is welcome.

Answer №1

Replace the a => lambda with mon += hours.MondayHours and so forth.

If not, when you do the second forEach, you are just generating multiple lambda functions without actually updating mon, tue, etc.

this.Projects.forEach(empHours => {
        empHours.TimeLoggedHours.forEach(hours => {
                mon += hours.MondayHours;
                tue += hours.TuesdayHours;
                wed += hours.WednesdayHours;
                thu += hours.ThursdayHours;
                fri += hours.FridayHours;
                sat += hours.SaturdayHours;
                sun += hours.SundayHours;
        });            
    });

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

Verify whether a specific value is present in an array (Laravel or Php)

I have the following array: $list_desings_ids = array('hc1wXBL7zCsdfMu','dhdsfHddfD','otheridshere'); When I use die() + var_dump() on this array, it returns: array:2 [▼ 0 => "hc1wXBL7zCsdfMu" 1 => " ...

What is the proper way to leverage the global 'window' object within Angular?

I'm attempting to utilize the method "window["initMapCallback"]" to invoke and monitor for "initMapCallback" in a separate file. However, I am encountering an error message in the debugging console that states Query - How can I properly implement thi ...

Contrasting characteristics of class members in JavaScript versus TypeScript

Typescript, a superset of Javascript, requires that Javascript code must function in Typescript. However, when attempting to create class members in a typescript file using the same approach as Javascript, an error is encountered. CODE :- script.ts (types ...

Unable to locate a type definition file for module 'vue-xxx'

I keep encountering an error whenever I attempt to add a 3rd party Vue.js library to my project: Could not find a declaration file for module 'vue-xxx' Libraries like 'vue-treeselect', 'vue-select', and 'vue-multiselect ...

The 'target' property is not found on the specified 'string' type

I've encountered an issue while creating a search bar in Typescript. Despite my efforts, the input is not being recognized. It seems that whenever I use the term 'target' in my onChange method, it triggers an error stating: Property &ap ...

Failure in validating a form in Angular 2

This is a form I have created: import { FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ template: ` <form [formGroup]="formGroup" (ngSubmit)="onSubmit()" novalidate> <textarea (keyup)="va ...

Encountered an error with API request while utilizing Cashfree in a React Native environment

I'm currently integrating cashfree into my react native app for processing payments. Here is a snippet of the code I'm using: import { CFPaymentGatewayService, CFErrorResponse, } from 'react-native-cashfree-pg-sdk'; import { CFDr ...

What is the reason for the removal of the `?` decorator in this mapped type? Are there alternative methods to achieve a similar outcome without eliminating it

Challenge In the process of creating a mapped type that excludes properties of type Function, we encountered an issue. Our current method not only eliminates functions but also strips away the optional decorator (?) from the mapped properties. Scenario ...

Using Angular's ElementRef to set focus on an ion-textarea: "The 'setFocus' property is not found on the 'ElementRef' type."

After developing a textarea component that automatically focuses itself when created using the ngAfterViewInit() method, everything seemed to be working perfectly as expected. ngAfterViewInit() { if(this.text.length===0){ this.theinput.setFocus(); ...

Preventing text from wrapping in a TypeScript-generated form: Tips and tricks

I’m currently working on a ReactJS project and my objective is simple: I want all three <FormItem> components to be displayed in a single line without wrapping. However, I am facing the following output: https://i.stack.imgur.com/mxiIE.png Within ...

Clicking the button in Angular should trigger a series of functions to be

It seems like I'm struggling with a simple question due to my lack of experience in this area. Any guidance or help would be greatly appreciated. I have a button that should trigger multiple functions when clicked, all defined in the same ts file. Wh ...

Angular Typescript filter function returning an empty arrayIn an Angular project, a

I have a filtering function in Angular that is returning an empty array. Despite trying similar solutions from previous questions, the issue persists. The function itself appears to be correct. Any assistance would be greatly appreciated. gifts represents ...

The most accurate type to determine after verifying that `typeof a === 'object' && a !== null` is the following

Within my codebase, there exists an assertion function that verifies a given value is an object (using the typeof operator), with the exception of null: export function assertIsJavaScriptObjectExceptNull(value: unknown) { if (typeof value !== 'obj ...

Imitating elegant angular input styles

Just before launch, the higher-ups have decided that they prefer a modern aesthetic for input controls - underlines rather than boxes, with labels that slide out of the way when the input is in focus. Check out the effect on this page: https://material.an ...

Typescript Next.js Project with Custom Link Button Type Definition

I have a project that includes a custom Button component and a NextLink wrapper. I want to merge these two components for organization purposes, but when I combine the props for each, I encounter an issue with spreading the rest in the prop destructuring s ...

Obtain unique entries from a Firestore collection search

Seeking assistance in filtering an observable to only contain unique records. I am using the observable in an angular mat-autocomplete with an async pipe and querying firebase based on the user's input. The code for the mat-autocomplete template: ...

typescriptExtract generic type from TypedDocumentNode<MyType, unknown> using introspection

I am currently utilizing a library that allows me to retrieve the type from a returned variable within a function. const myVar = gql(somestring) // The library function is called gql type myVarType = typeof myVar // The resultant value of myVarType is Typ ...

developed a website utilizing ASP MVC in combination with Angular 2 framework

When it comes to developing the front end, I prefer using Angular 2. For the back end, I stick with Asp MVC (not ASP CORE)... In a typical Asp MVC application, these are the steps usually taken to publish the app: Begin by right-clicking on the project ...

Failed to hit breakpoint in TypeScript file while working with Visual Studio 2019 and Webpack

We are working on an ASP.NET MVC 5 application where we are incorporating TypeScript for client-side code and using webpack to bundle everything into a single js file. TypeScript has been installed via npm. However, we have encountered an issue where setti ...

Utilizing an array element within a conditional statement

I am currently working on an analysis to plot a series of values across a range of time values represented by the variable t in an array format. Ux and Uy are functions of t, as are U1, U2, Ep1, and Ep2, due to their relationships. The issue arises at the ...