I'm working on small angular project. I have an array of receipt items, e.g. coke, fanta, pepsi, juice etc, with their prices and quantity of course.
receiptItems: Array<ReceiptItem>;
This is how ReceiptItem
looks :
export class ReceiptItem { public id: string; public product: Product; public unitOfMeasure: UnitOfMeasure; public discount: number; public price: number; public quantity: number; public total: number; public tax:Tax; }
How can I in typescript get sum of total amount but only where property tax for example is equal to "25%"?
In C# I remember I've used lambda expressions like this:
IEnumerable<ReceiptItems> results = receiptItems.Where(s => s.Tax == "25.00"); totalSum = results.Sum(x => (x.TotalAmount));
How to achieve something similar in TypeScript / Angular?
To sum a property in an array of objects:Initialize a sum variable, using the let keyword and set it to 0 . Call the forEach() method to iterate over the array. On each iteration, increment the sum variable with the value of the object.
function addNumbers(a: number, b: number) { return a + b; } var sum: number = addNumbers(10, 15) console. log('Sum of the two numbers is: ' +sum); The above TypeScript code defines the addNumbers() function, call it, and log the result in the browser's console. The above command will compile the TypeScript file add.
TypeScript - Array reduce() reduce() method applies a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
The reduce() method executes the function for each value of the array (non-empty array) from left to right. The reduce() method has the following syntax: let arr = [];arr. reduce(callback(acc, curVal, index, src), initVal);
Arrays in JavaScript/TypeScript also have these kind of methods. You can again filter
with you condition and then use reduce
aggregation function to sum the items.
const sum = receiptItems.filter(item => item.tax === '25.00') .reduce((sum, current) => sum + current.total, 0);
item.tax === '25.00'
- this part you must adjust with your logic
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With