根据多个过滤器 JavaScript 从 JSON 数据计算平均值

javascriptweb developmentfront end technologyobject oriented programmingjson

假设,我们有一个像这样的对象数组 −

const arr = [
   { "SupplierName" : "John", "Category" : "A", "Points" : 3 },
   { "SupplierName" : "John", "Category" : "A", "Points" : 11 },
   { "SupplierName" : "John", "Category" : "A", "Points" : undefined },
   { "SupplierName" : "John", "Category" : "B", "Points" : 2 },
   { "SupplierName" : "John", "Category" : "B", "Points" : 6 },
   { "SupplierName" : "Praveen", "Category" : "A", "Points" : 3 },
   { "SupplierName" : "Praveen", "Category" : "A", "Points" : 7 }
];

我们需要编写一个 JavaScript 函数来接收一个这样的数组。

该函数应该执行以下操作 −

  • 将重复的供应商分组为一个唯一的单独对象(重复是指具有相同 "SupplierName" 和 "Category" 字段的对象)。
  • 将他们的分数加在一起
  • 向每个对象添加一个新的 "average" 字段,其中包含该供应商的平均分数。

因此,最终输出应如下所示 −

const output = [
   { "SupplierName" : "John", "Category " : "A", "Points" : 14, "Average" : 7 },
   { "SupplierName" : "John", "Category " : "B", "Points" : 8, "Average" : 4 },
   { "SupplierName" : "Praveen", "Category " : "A", "Points" : 10, "Average" : 5 }
];

示例

const arr = [
   { "SupplierName" : "John", "Category " : "A", "Points" : 3 },
   { "SupplierName" : "John", "Category " : "A", "Points" : 11 },
   { "SupplierName" : "John", "Category " : "A", "Points" : undefined },
   { "SupplierName" : "John", "Category " : "B", "Points" : 2 },
   { "SupplierName" : "John", "Category " : "B", "Points" : 6 },
   { "SupplierName" : "Praveen", "Category " : "A", "Points" : 3 },
   { "SupplierName" : "Praveen", "Category " : "A", "Points" : 7 }
];
const groupAndAverage = (arr = []) => {
   const groups = arr.reduce((acc, obj) => {
       const name = obj.SupplierName + obj.Category;
      if (acc[name]) {
         if (obj.Points) (acc[name].Points += obj.Points) && ++acc[name].Average;
      }
      else { acc[name] = obj;
         acc[name].Average = 1;
         // taking 'Average' attribute as an items counter(on the first phase)
      };
      return acc;
   }, {});
   // getting "average of Points" const res = Object.keys(groups).map( name => {       groups[name].Average = Math.round(groups[name].Points/groups[name].Average);
      return groups[name];
   });
   return res;
}; console.log(JSON.stringify(groupAndAverage(arr), undefined, 4));

输出

控制台中的输出将是 −

[
   {
      "SupplierName": "John",
      "Category ": "A",
      "Points": 22,
      "Average": 6
   },
   {
      "SupplierName": "Praveen",
      "Category ": "A",
      "Points": 10,
      "Average": 5
   }
]

相关文章