The code provides a solution for grouping objects based on a common key, in this case, the ‘reference’ key. It takes an array of objects as input and creates a new array where objects with the same ‘reference’ value are grouped together. Additionally, it calculates the sum of the ‘amount’ values for objects within each group and updates the ‘amount’ key in the resulting array to reflect the summation.
By utilizing JavaScript’s reduce() method and object properties, the code efficiently iterates over the input array, maintains a collection of grouped objects, and dynamically adds new objects or updates existing ones. The final output is a structured array that facilitates easy access to objects grouped by their ‘reference’ value, along with the summed ‘amount’ value for each group.
function groupObjectsByReference(arr) {
const groupedObjects = {};
arr.forEach(obj => {
const reference = obj.reference;
if (groupedObjects.hasOwnProperty(reference)) {
groupedObjects[reference].amount += obj.amount;
groupedObjects[reference].objects.push(obj);
} else {
groupedObjects[reference] = {
reference: reference,
amount: obj.amount,
objects: [obj]
};
}
});
return Object.values(groupedObjects);
}
const originalArray = [
{
"reference": "P0332.A13 : P0332.A13.6 - ",
"memberAssociate": "205 - SUP121 FPAN Nepal",
"amount": 10
},
{
"reference": "P0332.A13 : P0332.A13.6 - ",
"memberAssociate": "205 - SUP121 FPAN Nepal",
"amount": 2
},
{
"reference": "P0777.A6 - ",
"memberAssociate": "205 - SUP121 FPAN Nepal",
"amount": 10
},
{
"reference": "P0797.A3 : P0797.A3.1 - ",
"memberAssociate": "205 - SUP121 FPAN Nepal",
"amount": 12
}
];
const groupedArray = groupObjectsByReference(originalArray);
console.log(groupedArray);
Output:
[
{
"reference": "P0332.A13 : P0332.A13.6 - ",
"amount": 12,
"objects": [
{
"reference": "P0332.A13 : P0332.A13.6 - ",
"memberAssociate": "205 - SUP121 FPAN Nepal",
"amount": 10
},
{
"reference": "P0332.A13 : P0332.A13.6 - ",
"memberAssociate": "205 - SUP121 FPAN Nepal",
"amount": 2
}
]
},
{
"reference": "P0777.A6 - ",
"amount": 10,
"objects": [
{
"reference": "P0777.A6 - ",
"memberAssociate": "205 - SUP121 FPAN Nepal",
"amount": 10
}
]
},
{
"reference": "P0797.A3 : P0797.A3.1 - ",
"amount": 12,
"objects": [
{
"reference": "P0797.A3 : P0797.A3.1 - ",
"memberAssociate": "205 - SUP121 FPAN Nepal",
"amount": 12
}
]
}
]