Finding the total of values within an array in Angular 2 and Ionic 2 by utilizing *ngfor

As I work on developing a mobile application using Ionic 2, my current task involves calculating the total allocation sum (Course.allocation) for each year per horse in the database.

For instance: Table: Course (Race):

[Id_course: 1, allocation: 200, date: 10/03/2012, idcheval: 1]

...

[Id_course: 4, allocation: 600, date: 10/03/2013, idcheval: 1]

Engagement table:

[2012, 2013]

The desired display format should be:

2012 ====> 500

2013 ====> 1300

I could really use some assistance with this. Can anyone help?

JSON

{
   // JSON data here
}

Template

<ion-row *ngFor="let ch of cheval1 ">
      {{ch[0].annee }}
    <div *ngFor="let m of members  ; let rowIndex = index">
            <ion-col *ngIf="ch[0].annee == (m.Course.date |date : 'yyyy' )">
            {{ m.Course.allocation}} 
            </ion-col>
     </div>

Component

allocationSum: number;
// other variables

getIdCheval() {

  this.allocationSum = this.members.reduce((previous, current) => {
    return previous + parseInt(current.Course.allocation);
  }, 0);
}

Answer №1

Applying map and reduce methods:

const data = [{ 
    Id_course: 1, 
    allocation: 200, 
    date: '10/03/2012', 
    idcheval: 1 },
    { 
    Id_course: 1, 
    allocation: 200, 
    date: '10/03/2012', 
    idcheval: 1 },{ 
    Id_course: 1, 
    allocation: 200, 
    date: '10/03/2014', 
    idcheval: 1 },
    { 
    Id_course: 1, 
    allocation: 200, 
    date: '10/03/2012', 
    idcheval: 1 }
    ];

var processedData = data.map((item) => ({ 
    allocation: item.allocation, 
    year: item.date.split('/').slice(-1)[0] 
}))
.sort((a, b) => +(b.year) - +(a.year))
.reduce((previouslyProcessed, current) => {
    const length = previouslyProcessed.length - 1;

    if (previouslyProcessed[length] && previouslyProcessed[length].year === current.year) {
        previouslyProcessed[length].allocation += current.allocation;
        return previouslyProcessed;
    }
    previouslyProcessed[length + 1] = current;
    return previouslyProcessed;
}, []);

for (const item of processedData) {
  console.log(`${item.year}\t=====>\t${item.allocation}`);
}

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

Issue with conflicting namespaces warning when compiling an Angular 9 project with ng-packagr using Typescript

I'm trying to pinpoint the root cause of this problem, and I suspect it may be related to Typescript. However, it could also involve ng-packagr or Angular. This issue only arose after upgrading to Angular 9. Upon building my production environment, I ...

How do I assign a default value to an optional parameter in a derived class in Typescript?

One of my classes is called ClientBase: export class ClientBase { constructor(private uri: string, private httpClient: HttpClient) { } // Contains Various Methods } I have multiple subclasses that are derived from the ClientBase For instance: @I ...

Learn the process of synchronously loading forms and data in Angular

Looking to synchronize the loading of data and form... Let's start by reviewing the code: ngOnInit() { if (this.data.fromCalendar) { this.singleTraining(); } }, 200); this.formControl(); } formControl() { this.gib ...

What might be the reason behind Array concatenation causing an issue in TypeScript?

I am relatively new to TypeScript and recently encountered an issue while working with classes. class DataStorage { private data:string[] = []; addItem(item: string){ this.data.push(item); } removeItem(item: string){ ...

Simulated custom error response object jasmine-Angular

Within the HTTP service, there is a single function designed to manage all HTTP errors, taking custom objects and displaying errors based on specific conditions. This is an example of the service function: get(path: string, params: HttpParams = new Http ...

Angular default route with parameters

Is it possible to set a default route with parameters in Angular, such as www.test.com/landing-page?uid=123&mode=front&sid=de8d4 const routes: Routes = [ { path: '', redirectTo: 'landing-page', pathMatch: 'full' }, ...

How to use Angular i18 for localizing the value of an interpolated string in a

In my Angular application, I have two translations in xliff format. The first one is @@field-is-required, which includes a string interpolation, and the second one is @@lastname, a regular translation. <trans-unit id="field-is-required" dataty ...

Angular 11 issue: Unable to display image on the webpage

When I try to view my image by directly using the URL in the src tag, it works fine. However, when I attempt to load it dynamically, an error is thrown. Even using [src]="img.ImagePath" method gives me the same response Here is the error logged ...

`Angular2 Reactively-shaped Form Elements with BehaviorSubject`

As a newcomer to Angular, I am struggling with updating reactive forms after making asynchronous calls. My specific challenge involves having a reactive form linked to an object model. Whenever there is a change in the form, it triggers an HTTP request th ...

Any idea how to resolve this typescript typing issue: "The argument, either a string or number, cannot be assigned to the parameter of type 'SetStateAction<string>'"?

Just recently delving into TypeScript, I've encountered a persistent typing problem that has proven challenging to resolve despite numerous attempts. The error message causing me trouble reads as follows: Argument of type 'string | number' ...

A guide on eliminating repetitions from an array of objects by utilizing the spread operator

I am working with an object array that has a unique key called "id": var test = [ {id: 1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""}, {id: 2, PlaceRef: "*00022", Component: "BAXI10R", SubLocCode: "KIT", BarCode:""}, {id: ...

Incorporating observables into an existing axios post request

Currently, I have an API using axios to send HTTP POST requests. These requests contain logs that are stored in a file. The entire log is sent at once when a user signs into the system. Now, I've been instructed to modify the code by incorporating Rx ...

TypeScript creates a .d.ts file that contains declaration statements rather than export declarations

When compiling my code using the command tsc --p typescript/tsconfig.json --outFile "dist/umd/index.d.ts", I encountered an issue. The contents of my tsconfig.json file are as follows: { "include": ["../src/**/*"], "exclude": ["../**/*.test.ts"], ...

Navigating with hashtags in Angular2 and anchors does not change the page position

I recently came across a helpful post that showed me how to append a fragment to the URL. Angular2 Routing with Hashtag to page anchor Although the fragment is successfully added, I'm encountering an issue where the page does not scroll to the speci ...

converting nested object structures in typescript

I'm trying to flatten a nested object in my Loopback and Typescript controller Here's the structure of my model : export class SampleModel { id: number; code: number; guide?: string; gradeData?: string; } Take a look at this example obj ...

How can I utilize formGroupName and pass it to a different component?

Here is the template I am working with: <mat-form-field class="dense no-bottom" appearance="fill" style="min-width: 8em; flex: 1;"><mat-label>{{ label | translate}}</mat-label><mat-select formControlName=& ...

Ionic 2 - Dynamically Loading Segments

I am dealing with categories and dishes. Each dish is associated with a specific category. My goal is to send an http request to retrieve all the dishes belonging to a particular category. This will result in an array like: { Soup[{'Name',&ap ...

Is it beneficial to use both Bootstrap and ng-bootstrap together?

I have two modules in my angular website - "bootstrap" and "ng-bootstrap". Do I need both or just one? I am thinking of keeping only "ng-bootstrap" 4.0.0.0 and removing "bootstrap". Is this acceptable? What are the steps to remove "Bootstrap"? Can I simp ...

Wrong method executed when trying to use Angular http put

I am facing an issue with my http.put wrapper where it is calling the incorrect PUT overload. I specifically need the one that returns Observable<Object>, but instead it is calling Observable<ArrayBuffer>. Here is the code snippet for my http.p ...

Creating a Lambda function in CDK: A guide to configuring the Dockerfile and setting environment variables

I am currently working on a SAM project using template.yml. Here is a snippet of the configuration: Globals: Function: Timeout: 30 Environment: Variables: DBNAME: !Ref DBNAME Resources: MessageFunction: Type: AWS::Serverless: ...