假设我们有一个像这样的对象数组-
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; //将“平均”属性作为项目计数器(在第一阶段) }; 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 } ]