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!
Answer
- You can use
.reduce
to create an object withCountry
askeys
and the sum ofAmount
asvalues
- Then, sort these pairs according to the
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