12

I have list of objects with balances (there are other properties in objects but not imported for example):

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

I am looking for smart pipe that would sum (other would average) balances in array (would prefer not using for loop - but some ES6 functionality like reduce but not sure how)

1 Answer 1

26

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

Sum

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 how you would any other pipe

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

Average

For an average pipe, just use the similar logic as the sum pipe. This treats null as 0.

transform(items: any, attr: string): any {
    let sum = items.reduce((a, b) => a + b[attr], 0);
    return sum / items.length;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for a great solution. I expanded it to include flat arrays (without the attribute), like so: if (attr) { sum = items.reduce((a, b) => a + b[attr], 0); } else { sum = items.reduce((a, b) => a + b, 0); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.