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

A comprehensive guide on extracting data from the query string in Angular

There is a specific query string format that we need to handle. The input parameter of the method comes in the form of a string and it's not an instance of ActivatedRoute. http://localhost:4200/users?param1=en&param2=nk I've attempted to rea ...

Is it advisable to send a response in Express.js or not?

When working with Express.js 4.x, I'm unsure whether to return the response (or next function) or not. So, which is preferred: Option A: app.get('/url', (req, res) => { res.send(200, { message: 'ok' }); }); Or Option B: ...

Stop the inheritance of static components in a feature module by protecting the router-outlet

I am in the process of dividing my app into multiple feature modules. Currently, I am using only the router-outlet inside a component within a feature module. However, this approach brings along all the static components such as the navbar and footer. How ...

Refreshing Form in Angular 2

When I remove a form control from my form, it causes the form to always be invalid. However, if I delete a character from another input field and then add the same character back in (to trigger a change event), the form becomes valid as expected. Is ther ...

Encountered an issue finding element with Protractor - Error: script timed out after 20 seconds without receiving a response

I recently created a basic website using Angular 6 and I am facing some challenges while writing e2e tests for it. The first script is causing a lot of trouble for me as it throws the following error: C:\Users\user\Documents\workspace- ...

Steps to show the chosen index value in an alert pop-up using Ionic 2 framework

I'm in the process of trying to showcase a selected index value within an Ionic 2 alert box. However, I'm struggling to find the correct method to display it in the Ionic prompt. This pertains to the home.ts import { Component } from '@ang ...

Why does my Visual Studio Code always display "building" when I launch an extension?

https://code.visualstudio.com/api/get-started/your-first-extension I followed a tutorial to create a hello world extension. Why does my VSCode always display 'building' when I run the extension? Executing task: npm run watch < [email p ...

Issue with ESLint error in TypeScript PrimeReact async Button click handler

I am currently facing an issue with exporting data from a DataTable in PrimeReact. The onClick function for the Button does not allow async callbacks as flagged by eslint. Can someone guide me on how to properly call this function? const exportCSV = us ...

Display the highlighted text within the input field

Is there a library available that can create an input field with a suggestions dropdown for Male and Female where typing "M" will highlight the letters "ale," allowing for autopopulation when clicked or tabbed? The same functionality should apply for typin ...

rxjs - straightforward issue with initiating observables

I'm currently tackling an assignment that involves setting up a basic form with input fields for 'From', 'To', and 'Duration' using rxjs. While it might be easier to just utilize getter / setters, I'm determined to ...

The implementation of the new package is causing a disruption in my project

I've encountered an issue while trying to integrate bcryptjs into my application. Although I successfully installed it, the development environment crashes upon startup. The project is currently built on angular v6, and after running npm install to do ...

Problem with moving functions from one file to another file via export and import

I currently have the following file structure: ---utilities -----index.ts -----tools.ts allfunctions.ts Within the tools.ts file, I have defined several functions that I export using export const. One of them is the helloWorld function: export const hel ...

Determining when to include @types/packagename in React Native's dev dependencies for a specific package

Just getting started with React Native using typescript. Take the package vector icon for example, we need to include 2 dependencies: 1. "react-native-vector-icons": "^7.1.0" (as a dependency) 2. "@types/react-native-vector-icons": "^6.4.6" (as a dev ...

Exploring the power of Angular's ViewChildren to iterate through QueryList items

My ngFor loop includes child components: @ViewChildren(SingleMultiSelectionComponent) singleMultiSelections: QueryList<SingleMultiSelectionComponent>; I am attempting to iterate through this QueryList: console.log(this.singleMultiSelections); // 1 i ...

The search for d.ts declaration files in the project by 'typeRoots' fails

// Within tsconfig.json under "compilerOptions" "typeRoots": ["./@types", "./node_modules/@types"], // Define custom types for Express Request in {projectRoot}/@types/express/index.d.ts declare global { namespace Express { interface Request { ...

The API request does not provide randomized results and does not show any display

I am facing an issue with a button that is supposed to fetch a random user from an API. When I retrieve all the users, the information is displayed correctly. However, when I try to select a user at random, it does not work as expected. Also, it seems to a ...

TypeScript's standard React.Children interface for compound components

One of my components is a Table, which can have children that are Column components: <Table data={data}> <Column cell={(c) => c.date} header="Date" /> <Column cell={(c) => c.count} header="Count" /> & ...

Dynamic tag names can be utilized with ref in TypeScript

In my current setup, I have a component with a dynamic tag name that can either be div or fieldset, based on the value of the group prop returned from our useForm hook. const FormGroup = React.forwardRef< HTMLFieldSetElement | HTMLDivElement, React. ...

Verify if the currentRoute begins with a specific text pattern (such as something/something/*...) in Angular

I need to prevent a loader from appearing on certain screens, so I used ngIf on routes where the loader is not necessary. Here's the code snippet from app.component.ts : <router-outlet> <app-spinner></app-spinner> <ngx-ui-load ...

Special characters in JSON files may cause loading issues in Nativescript Angular

Can someone help me with an issue I'm having while trying to retrieve a JSON file from the server using a GET method? { "myKey": [{ "code" : "RMB", "symbol" : "¥", }] } When making the Nativescript GET request, ev ...