-1

I'm currently getting my data from an API. It stores the weight log of animal checkups as shown below.

Currently I'm storing it in a html tag:

<h3 className='dogWeight'>Average: {item.weight}%</h3>

But it prints the numbers together as a string (i.e 100102103). Is there anyway I can add all numbers in the array to just show the Average?

{
   "dog":[
      {
         "weight":[
            "78",
            "100",
            "92",
            "86",
            "89",
            "88",
            "91",
            "87"
         ],
         "id":"1",

      },
      {
         "weight":[
            "75",
            "89",
            "95",
            "93",
            "99",
            "82",
            "89",
            "76"
         ],
         "id":"2",

      },
rickandmorty
  • 165
  • 2
  • 8

1 Answers1

1

You can loop over data.dog and reduce the weight values by accumulating the parsed integer weight values and dividing by the length of the weight array.

const data = {
  "dog": [{
    "id": "1",
    "weight": [  "78", "100", "92", "86", "89", "88", "91", "87" ],
  }, {
    "id": "2",
    "weight": [ "75", "89", "95", "93", "99", "82", "89", "76" ],
 }]
};

const avg = vals => vals.reduce((sum, x) => sum + parseInt(x, 10), 0) / vals.length;

data.dog.forEach(({ id, weight }) =>
  console.log(`ID: ${id}, Avg Weight: ${avg(weight).toFixed(2)}%`));
.as-console-wrapper { top: 0; max-heightL 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132