根据多个筛选条件从 JSON 数据中计算平均值 JavaScript


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

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”字段相同的对象)。
  • 将它们的积分加在一起
  • 向每个对象添加一个新的“平均值”字段,其中包含该供应商的平均积分。

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

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
   }
]

更新于: 23-11-2020

1 千+ 浏览

开启你的职业生涯

完成课程获得认证

立即开始
广告