Read from local database and sum values

I have a local database (resource id: Avoided) with a couple of properties. One of them is called Grams. I can add new entry’s, make lists and edit a single but i have no clue how to go from there. I want to loop through all the records and sum all values with the property “Grams” and put that in a page variable.

(New user alert: I just started two evenings ago with Appgyver…)

After hours of searching i found a solution. Please correct me if there is a better way to do this:

First I set a page variable called “avoidedFood” (all types) with formula: MAP(data.avoided_list, {value: item.Avoided})
Then i set a page variable called “sum” with formula: SUM_BY_KEY(pageVars.avoidedFood, “value”).

This gives me a page variable with all the record summarized.

You can also do this in one step by using REDUCE_INIT, which is really powerful. It computes a numerical quantity from a list of items, but the beauty is you get to specify a formula for the contribution of each item. The first argument is your list of items to process, the 2nd is the initial value (usually 0), and the 3rd is a function that is run on each item in your list. By using ‘accumulator’ in that function, you can sum the contribution of each item per your formula.

As an example, I wanted to calculate the total price of a list of items, each of which could have multiples at a given price, but only include items that had been paid for. So for items with item.purchase TRUE, add the price * quantity. For items with item.purchase FALSE, add nothing. Was able to do that in a single function:

REDUCE_INIT(appVars.itemList, 0, accumulator + IF(item.purchased, NUMBER(item.price)*NUMBER(item.qty),0))


Thanks! That also did the trick.