Get average depending on the selected fields

I would like to obtain the average of the fields in use.
Example:
Product Potatos Banana Apple Carrot
Quantity 4 2 0 0
Product Average 3 // formule (4+2) / 2 ), two product in use.

Product Potatos Banana Apple Carrot
Quantity 4 2 6 0
Product Average 4 // formule (4+2+6) / 3 ), three product in use.

In product Average need a function onReady, to display information on screen. I really dont know what code use for this. Can you help me guys? I can get the average from static values, but if the fields changes, i need divide just for the selected values.

Inside onReady try to make a function that will:

  • fetch all the data from a database ( https://www.wix.com/corvid/reference/wix-data.WixDataQuery.html )
  • go over the received array for loop / forEach / map
  • filter out the values that contain 0 (inside the loop)
  • calculate the sum of all values that contain other number that 0 (also inside the loop)
  • divide it by values count (inside the loop)
1 Like

Hello Viktoriia.
Im trying with this, i dont know if is the right way… for the moment i can sum 1 value, but dont worth. :frowning:

import wixData from 'wix-data';

$w.onReady(function () {
let count = $w("#dataset1").getTotalCount(); // No. of items in dataset //
$w("#dataset1").getItems(0, count) // Get all items //
.then((results) => {
 let sumTotal = 0;
 let items = results.items;
    items.forEach(item => {
         sumTotal = sumTotal + Number(item.potatos)  
                             + Number(item.banana)
                             + Number(item.apple) 
                             + Number(item.carrot);
    });
    $w("#productAverage").text = "" + sumTotal;

    }).catch((err) => {
     console.log(err);
    });
});

Do you have some similar code for guide me?
I’d be really grateful.