Home > Enterprise >  Getting the average of the numbers on each month javascript
Getting the average of the numbers on each month javascript

Time:06-22

Any idea how can I get the average of the numbers on each month.

let techScores = [
      {
        "2021-01":[78,86,100],
        "2021-02":[100,100,92],
        "2021-03":[86]
      },
      {
        "2021-01":[68,100,84],
        "2021-02":[82,92,82],
        "2021-03":[86,100,100,90,100]
      }
    ]

How to get the average of the numbers in each of the month and year. This is the output i tried to get

total_ave 91

total_ave 97.3

total_ave 86

total_ave 84

total_ave 85.3

total_ave 95.2

CodePudding user response:

Use Array#flatMap obtain an array of score sub arrays:

[[78,86,100],[100,100,92],[86],[68,100,84],[82,92,82],[86,100,100,90,100]]

Then use Array#map on this array, and Array#reduce on each sub array to sum the scores and divide by their count to get the average:

[88,97.33333333333333,86,84,85.33333333333333,95.2]

const techScores = [ { "2021-01":[78,86,100], "2021-02":[100,100,92], "2021-03":[86] }, { "2021-01":[68,100,84], "2021-02":[82,92,82], "2021-03":[86,100,100,90,100] } ],
    
      output = techScores
      //Get just the scores in an array with each set as a sub array
      .flatMap(o => Object.values(o))
      //Evaluate the average of each sub array
      .map(
          scores => 
          scores.reduce(
              (total, current) => total   current, 0
          )
          /scores.length
      );
    
console.log( output );

CodePudding user response:

Loop over main array "techScores", then loop over properties of each object using Object.keys() methods, get reference of value of each property(in this case it's array of numbers). Finally calculate average of number instead array.

techScores.forEach(obj=>{
          Object.keys(obj).forEach(key=>{
              const arr = obj[key]
              let sum = 0
              arr.forEach(number=>sum =number)
              const avg = sum / arr.length
              console.log(`total_ave ${avg.toFixed(1)}`)
          })
      })
  • Related