Sum values from database and display value in element

Hello,

I am trying to sum values from a database and display the result in an input element. I am not sure how to go about this. I have tried the below code, but the value it is giving me is incorrect. Does anybody have suggestions on how I can properly accomplish this? I want to sum the values from the Count Items column, (field key countItems), located in the member-File database.

export function button12_click(event, $w) {
wixData.query(“member-File”).find().then( (results) => {
const items = results.items;
let sumamount = 0;
items.forEach(yard => {
sumamount += yard.countItems;
});
$w(‘#input7’).value = sumamount}
) . catch ( (err) => { let errorMsg = err; } );
}

Use reduce() instead of forEach().
reduce method:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Sum_of_values_in_an_object_array

Thank you for the quick reply, J.D.

I am unable to get anything to display when I use reduce() instead of forEach().

To clarify, I have a table that is filtered by dropdown selections. I would like the input element (‘#input7’) to display the sum of the values in the table when a button (button12) is clicked.

Does this make sense?

@cale

//......
.then((results) => {
const items = results.items;
let initialValue = 0;
let sum = items.reduce(function (accumulator, currentValue) {
    return accumulator + currentValue.x;// instead of .x use your field key.
},initialValue);
   $w('#input7').value = sum; 
})
//....

Hello J.D.

I tried the above and still cannot get it to work. I have tried the below as well. It is close… it is summing everything for that email and wont display in the input element on the page.

export function button12_click(event,$w) {
const filter = (wixData.filter().eq(“yard”, $w(“#yarddropdown”).value) && wixData.filter().eq(“email”, $w(“#input3”).value))
wixData.aggregate(“member-File”)
.filter(filter)
.sum(“countItems”)
.run()
.then( (results) => {
if (results.items.length > 0) {
let items = results.items;
$w(‘#input7’).value = results.items;
}
console.log(results.items);

} );

}

my code above is supposed to work. maybe if you post here the code, I’ll be able to see how you applied it and correct the problems.