Fares K. A. - 3 months ago 7

Javascript Question

I have an array of objects. I don't know how many objects there will be until the code is being run (it is returned from an API), but let's assume this is the array:

`var arr = [ { A: 40, B: 88, C: 11 },`

{ A: 10, B: 98, C: 65 }, // sum of A = 188

{ A: 11, B: 15, C: 18 }, // sum of B = 310

{ A: 16, B: 55, C: 16 }, // sum of C = 136

{ A: 22, B: 23, C: 13 },

{ A: 89, B: 31, C: 13 } ]

I want to look over every object in the array. I'd like the end-result to be a list of keys and values, sorted in descending order. So, if we were to use the array above, the code would return something like this:

`[["B", 310], ["A", 188], ["C", 136]]`

I hope it's not too much to ask if you can add comments in your code, as sometimes the answers here can be very short and efficient (and work brilliantly) but difficult to understand for a beginner with algorithms :)

Many thanks in advance.

Answer

If you are about to get sorted result -like you mentioned in your terms- for your complete array then this may be the answer.

You can first calculate sum of corresponding properties of every object in the `arr`

ay with a simple `Array.prototype.reduce`

then convert the result to the structure you want (I preferred to loop over object keys) and then sort your structured array.

```
var arr = [ { A: 40, B: 88, C: 11 },
{ A: 10, B: 98, C: 65 },
{ A: 11, B: 15, C: 18 },
{ A: 16, B: 55, C: 16 },
{ A: 22, B: 23, C: 13 },
{ A: 89, B: 31, C: 13 }
];
var sum = arr.reduce((p, c) => {
var result = Object.create(null);
Object.keys(p).forEach(k => result[k] = p[k] + c[k]);
return result;
});
var sorted = Object.keys(sum).map(k => [k, sum[k]]).sort((a, b) => a[1] - b[1]);
console.log(sorted);
```