-1

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!

2
  • Show us what you have tried. SO isn't a free code writing service. The objective here is for you to post your attempts to solve your own issue and others help when they don't work as expected. See How to Ask and minimal reproducible example Commented Mar 7, 2021 at 15:52
  • Sorry about that, I have amended the question with my code Commented Mar 7, 2021 at 16:07

1 Answer 1

1
  • You can use .reduce to create an object with Country as keys and the sum of Amount as values
  • 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

Sign up to request clarification or add additional context in comments.

4 Comments

Best solution, IMO no other Array method will be more appropriate.
Thanks very much for this - and sorry about not posting code at start. I have amended the question now but don't want to mark as the solution just yet as this solves for the interim steps from my wrongly outputted JSON to the correctly desired JSON which might confuse people.
@ewldh20 I updated the answer with the new specifications
Thanks very much - I have marked it as working :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.