I am using JavaScript and currently I have
filteredObj =
[{Amount: 100, Country: "England"},
{Amount: 100, Country: "England"},
{Amount: 200, Country: "England"},
{Amount: 300, Country: "China"},
{Amount: 200, Country: "China"},
{Amount: 100, Country: "England"},
{Amount: 400, Country: "England"},
{Amount: 300, Country: "China"}]
How can I convert this to
condensedObj = [{China: 800,
England: 900}]
The following combines the code but keeps them in separate {}s i.e.
condensedObj =
[{Country: "China",
Amount: 800},
{country: "England",
Amount: 900}]
Current code:
condensedObj = filteredObj
.reduce(
function (res, obj) {
if (!(obj['Country'] in res))
res.__array.push(
(res[obj['Country'] = obj)
);
else {
res[obj['Country'].Amount +=
obj.Amount;
}
return res;
},
{ __array: [] }
)
.__array.sort(function (a, b) {
return b.Amount - a.Amount;
});
Thanks!