[Chartjs]-How to sum/divide array values in chart.js?

0👍

Just loop over the json array and then add the values to the sum variable and then add it to chart.

This code will do:

var sum=0;
for(item of myJSON)
{
    let subsum=item["Value 1"]+item["Value 2"]+item["Value 3"];
    sum+=subsum;
}

Then update the code like this:

var datiedu2 = {
            "labels": ['Lavori non terminati', 'Lavori in corso'],
            "datasets": 
                      [{
                           label: 'Numero',
                           data: sum,
                           backgroundColor: 'rgb(255, 99, 132)',
                           borderWidth: 1
                      }]
               };

0👍

Sums the properties Value 1 and Value 2

var myJSON = [{
    "": 0,
    "Comune": "BONDENO",
    "PUNTEGGIOSCUOLA1516": 4.25,
    "Value 1": 63,
    "Value 2": 8,
    "Value 3": 17,
    "DANNO": 6,
    "Somma valori": 88,
  },
  {
    "": 1,
    "Comune": "CAVEZZO",
    "PUNTEGGIOSCUOLA1516": 3.75,
    "Value 1": 23,
    "Value 2": 2,
    "Value 3": 9,
    "DANNO": 8,
    "Somma valori": 34,

  }
];



function getSum(arr) {
  const sum = arr.reduce((acc, x) => acc + x['Value 1'] + x['Value 2'], 0);
  return sum;

}
const result = getSum(myJSON);
console.log(result)

Leave a comment