Angular 2 pipe - calculating a summary of an array of objects

I have a list of objects with balances (objects have other properties, but not imported):

[{ balance : 100 },{ balance : 200 },{ balance : null },{ balance : 300 }]

I'm looking for a smart pipe that will summarize (other average) balances in an array (would prefer not to use it for a loop - but some ES6 features seem to reduce, but are not sure how)

+4
source share
1 answer

You will need to write your own tube, below should give you what you need. It takes the attribute of the object you want to sum as a parameter

Amount

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'sum'
})
export class SumPipe implements PipeTransform {
    transform(items: any[], attr: string): any {
        return items.reduce((a, b) => a + b[attr], 0);
    }
}

Use it like you would use any other channel

<span>{{ balances | sum:'balances' }}</span>

The average

, . null 0.

transform(items: any, attr: string): any {
    let sum = items.reduce((a, b) => a + b[attr], 0);
    return sum / items.length;
}
+11

Source: https://habr.com/ru/post/1669397/


All Articles