Suppose, we have an array of objects like this −
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 } ];
We are required to write a JavaScript function that takes in one such array.
The function should do the following things −
- Group repeating suppliers into one unique separate object (by repeating, we mean objects with same "SupplierName" and "Category" field).
- Add up their points together
- Add a new "average field to each object, containing the average points of that supplier.
So, finally the output should look like −
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 } ];
Example
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));
Output
And the output in the console will be −
[ { "SupplierName": "John", "Category ": "A", "Points": 22, "Average": 6 }, { "SupplierName": "Praveen", "Category ": "A", "Points": 10, "Average": 5 } ]