Search code examples
arraysangulartypescriptangular6

Find smallest & largest element in Array Angular & Typescript


Hello All I have array & i need to perform various operation like sum, total, average. All these 3 are achieved, Now I need to find the minimum & maximum value in array. I am stucked on this below is the code.

Below is TS Part

people: Array<number> = [1, 2, 3, 4, 5];
  total: number = 0;
  arrayLength: number = this.people.length;
  average: number = 0;

  sum() {
    for (var i in this.people) { this.total += this.people[i]; }
  }

  ngOnInit() {
    this.sum();
    this.average = (this.total / this.arrayLength);
  }

Below is HTML Part

<span *ngFor="let p of people" style="font-size:18px">{{p}} </span><br><br>
<button >Quantity</button> = {{arrayLength}}<Br><br>
<button >Average</button> = {{average}}<Br><br>
<button >Sum</button> <span *ngIf="sumShow"> = {{total}}</span><Br><br>

Solution

  • use reduce for this.

    Demo on Stackblitz

      sum() {
        this.total = this.people.reduce((a, b)=>a + b); 
      }
    
      ngOnInit() {
        this.sum();
        this.max = this.people.reduce((a, b)=>Math.max(a, b)); 
        this.min = this.people.reduce((a, b)=>Math.min(a, b)); 
        this.average = (this.total / this.arrayLength);
      }
    
    
    <span *ngFor="let p of people" style="font-size:18px">{{p}} </span><br><br>
    <button >Quantity</button> = {{arrayLength}}<Br><br>
    <button >Average</button> = {{average}}<Br><br>
    <button >Sum</button> <span > = {{total}}</span><Br><br>
    
    <button >Max</button> <span > = {{max}}</span><Br><br>
    <button >Min</button> <span > = {{min}}</span><Br><br>