I have an array of products, each product has a price. I want to create a filter to calculate the total price of all products. The problem is that I can't use forEach() since I'm in a callback function. My question is, is there a function that does something like myArray.(intheobject).price, or a way to manage the callback and get the right results?
this.productList = [
{
type: 'chocolate',
pack: '3',
price: 5,
checkState: false
},
{
type: 'chocolate',
pack: '5',
price: 7,
checkState: false
},
{
type: 'chocolate',
pack: '10',
price: 10,
checkState: false
},
{
type: 'honey',
pack: '3',
price: 5,
checkState: false
},
{
type: 'honey',
pack: '5',
price: 7,
checkState: false
},
{
type: 'honey',
pack: '10',
price: 10,
checkState: false
},
{
type: 'candy',
pack: '3',
price: 5,
checkState: false
},
{
type: 'candy',
pack: '5',
price: 7,
checkState: false
},
{
type: 'candy',
pack: '10',
price: 10,
checkState: false
}
]
.filter('calculateTotal', function(){
var totalCost = 0;
return function(input){
return totalCost + ???
}
})
After PierreDuc's answer, my filter is this:
.filter('calculateTotal', function(){
return function(input){
return input.reduce((total, item) => item.price + total, 0);
}
})