Reputation: 93
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!
Upvotes: 0
Views: 35
Reputation: 28424
.reduce
to create an object with Country
as keys
and the sum of Amount
as values
value
(Amount) as follows:const arr = [
{ 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" }
];
const countries = arr.reduce((acc, {Amount,Country}) =>
({ ...acc, [Country]: (acc[Country] || 0) + Amount })
, {});
const sorted = Object.fromEntries(
Object.entries(countries).sort(([,amountA],[,amountB]) => amountA - amountB)
);
const res = [ sorted ];
console.log(res);
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries
Upvotes: 2