When attempting to group the array based on the destination
property, you can utilize a versatile groupBy
function in TypeScript. This function constructs a Map
(compatible with ES2015 or newer) mapping destination
values to arrays of objects sharing that specific value for destination
:
function groupBy<T, K extends keyof T>(key: K, arr: T[]): Map<T[K], T[]> {
const map = new Map<T[K], T[]>();
arr.forEach(t => {
if (!map.has(t[key])) {
map.set(t[key], []);
}
map.get(t[key])!.push(t);
})
return map;
}
Next, taking into consideration your provided input:
const input = [
{
origin: "XX",
destination: "YY",
volume: 500
},
{
origin: "ZZ",
destination: "YY",
volume: 500
}
]
You can transform the array entries from the grouped Map
into an array of objects that contains the grouped destination
and calculates the sum of volume
for each specified group:
const output = Array.from(groupBy("destination", input).entries())
.map(([dest, objs]) => ({
destination: dest,
volume: objs.reduce((acc, cur) => acc + cur.volume, 0)
}))
console.log(JSON.stringify(output)); // generates the desired result
May this solution assist you in your endeavors! Best of luck!
I have successfully tested this code snippet in the TypeScript Playground using v2.5.1 as per the current date. Feel free to explore it further by visiting here.