Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate average from data in array of object and store in specific key from object

Suppose I have an array of object,

const book = [{'name':'alpha','readingTime':1231},{'name':'alpha','readingTime':1254}, 
              {'name':'beta','readingTime':190},
              {'name':'theta','readingTime':909},{'name':'theta','readingTime':10}]

I want to calculate average for each name, such that expected O/P is

**{alpha:1242.5, beta:190, theta:459.5}**

For this I tried as ,

let calculatedValue = book.reduce((acc,curr) => acc+curr.readingTime,0)/book.length

This gives me average for all the object.

I'm unable to form logic corresponding to it.

Any guidance would really be helpful. If anyone needs any further information please let me know.

like image 378
Siva Pradhan Avatar asked Oct 27 '25 14:10

Siva Pradhan


2 Answers

You could group by name and get the count and total of readingTime and build a new object with the averages.

const
    books = [{ name: 'alpha', readingTime: 1231 }, {  name: 'alpha', readingTime: 1254 }, { name: 'beta', readingTime: 190 }, { name: 'theta', readingTime: 909 }, { name: 'theta', readingTime: 10 }],
    averages = Object.fromEntries(
        Object.entries(books.reduce((r, { name, readingTime }) => {
            r[name] = r[name] || { count: 0, total: 0 };
            r[name].count++;
            r[name].total += readingTime;
            return r;
        }, {}))
        .map(([k, { count, total }]) => [k, total / count])
    );

console.log(averages);
like image 167
Nina Scholz Avatar answered Oct 30 '25 05:10

Nina Scholz


Need more optimization (Fell free to edit ) but it works

const book = [{'name':'alpha','readingTime':1231},{'name':'alpha','readingTime':1254}, 
              {'name':'beta','readingTime':190},
              {'name':'theta','readingTime':909},{'name':'theta','readingTime':10}]


function avgReading(arr){
let alpha = { lengtharr : 0 ,readingAll : 0 };
let beta = {...alpha};
let theta = {...alpha};
arr.forEach((item) => {
  if(item.name === 'alpha') 
    alpha.lengtharr++;
    alpha.readingAll = alpha.readingAll + item.readingTime;
  if(item.name === 'beta') 
    beta.lengtharr++;
    beta.readingAll = beta.readingAll + item.readingTime;
 if(item.name === 'theta')
    theta.lengtharr++;
    theta.readingAll = theta.readingAll + item.readingTime;
});
const obj = {
'alpha' : alpha.readingAll /alpha.lengtharr,
'beta' : beta.readingAll /beta.lengtharr,
'theta' : theta.readingAll /theta.lengtharr
}
return obj;
}
console.log(avgReading(book))
like image 36
Anil Avatar answered Oct 30 '25 03:10

Anil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!