I have an array that contains objects structured like this:
[
{
"id": 91,
"factor": 2,
"title": "Test Product",
"price": 50,
"interval": 1,
"setup": 0,
"optional": false
},
{
"id": 92,
"factor": 1,
"title": "Another Test Product",
"price": 95,
"interval": 1,
"setup": 99,
"optional": true
},
{
"id": 93,
"factor": 1,
"title": "Just Another Test Product",
"price": 12,
"interval": 1,
"setup": 0,
"optional": false
}
]
Now, I want to calculate the following sums:
- Total setup cost
- Total price
- Price total for products based on intervals (grouped by 1, 2, 3, 4, ...)
Currently, I am using computed methods for each calculation:
setupTotal: function () {
return this.products.reduce ((acc, product) => acc + (parseFloat (product.setup) * parseFloat (product.factor)), 0);
},
and
monthlyCostsTotal: function () {
let sum = 0;
this.products.forEach (function (product) {
if (product.interval == 1) {
sum += (parseFloat (product.price) * parseFloat (product.factor));
}
});
return sum;
},
and
setupOptional: function () {
let sum = 0;
this.products.forEach (function (product) {
if (product.optional) {
sum += (parseFloat (product.setup) * parseFloat (product.factor));
}
});
return sum;
},
However, looping through the array multiple times is not efficient.
My question now is how can I improve the efficiency of calculating the following values:
- Total price
- Price for optional products only
- Total setup cost
- Setup cost for optional products only
- Price by interval