How to group by, calculate sum and get average in JavaScript array?

后端 未结 1 1485
陌清茗
陌清茗 2021-01-17 04:45

I have array of object

 const users = [
     { group: \'editor\', name: \'Adam\', age: 23 },
     { group: \'admin\', n         


        
相关标签:
1条回答
  • 2021-01-17 05:04

    You could simply use reduce to get the total of age groups.

    And use object.keys length to get the average of your total as new object from getAvg function.

    Demo:

    const users = [{
        group: 'editor',
        name: 'Adam',
        age: 23
      },
      {
        group: 'admin',
        name: 'John',
        age: 28
      },
      {
        group: 'editor',
        name: 'William',
        age: 34
      },
      {
        group: 'admin',
        name: 'Oliver',
        age: 28
      }
    ];
    
    const sumId = users.reduce((a, {
      group,
      age
    }) => (a[group] = (a[group] || 0) + age, a), {});
    
    console.log(sumId); //{editor: 57, admin: 56}
    
    //Average
    const getAvg = (x) => {
      const item = {}
      const count = Object.keys(x).length
      Object.keys(x).map(function(y) {
        item[y] = sumId[y] / count
      })
      return item
    }
    console.log(getAvg(sumId)); //{editor: 28.5, admin: 28}

    0 讨论(0)
提交回复
热议问题