Skip to content
Advertisement

filter value of select to do a partial sum

Having two classes professor and student:

  • professor.ts
    export class Professor {
        id: number
        name: string
    }
  • student.ts
    import { Professor } from "./professor"
    
    export class Student {
        id: number
        name: string
        score: number
        professor: Professor
    }

To add up the scores of each student relative to his teacher I did:

sel: number[] = []
prof: Professor[]
stud: Student[]
totalScore: number
partial: number
var: boolean = false

total() {
const total = this.stud
    .filter(c => this.sel.map(m => +m).includes(c.id))
    .reduce((a, c) => a + c.score, 0);
    this.totalScore = total
    this.var = true
}

This is the HTML of the page:

<div name="professors" *ngFor="let p of prof; index as j">
              {{ p.name }}
              <select name="students{{j}}" [(ngModel)]="sel[j]" class="form-control">
                <ng-container *ngFor="let s of stud; index as i">
                  <option *ngIf="s.professor.id === p.id" [value]="s.id">
                    {{ s.name }} <p>|</p>
                    {{ s.score }} 
                  </option>            
                </ng-container>
              </select>
              <label></label>
            </div>

      <button type="submit" (click)="total()"
      class="btn btn-primary">Go</button>

      <div *ngIf="var">          
         <p>Total: {{totalScore}}<br>
         <!--Partial sum: {{partial}}-->
         </p>  
      </div>

How can I do a partial sum of the selections, assuming for example that I have 5 professor with 1 student for every professor, and want to add only the results of the first 3 student. This is the stackblitz: https://stackblitz.com/edit/angular-ivy-sjs7fg?file=src/app/app.component.ts

Advertisement

Answer

Change your total method to :-

total() {
const total = this.stud
    .filter(c => this.sel.map(m => +m).includes(c.id))
    .slice(0,3)
    .reduce((a, c) => a + c.score, 0);
    this.totalScore = total
    this.variable = true
}

working stackblitz :- https://stackblitz.com/edit/angular-ivy-nkxswo?file=src/app/app.component.ts

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement