HeelMega
HeelMega

Reputation: 508

Sum and average values of multiple objects in an array into one array

I have an array with multiple objects. I want to get the average and sum of their values.

Example original array:

[[{count: 2}],[{count: 10}]]

Final array:

Sum array: [{count: 12}]
Average array: [{count: 6}]

I tried using reduce... but it doesn't work if I have multiple keys in the array as it returns one number only.

Any idea how I would approach this?

for(var i = 0; i < arr.length; i++){
    let average = arr[i].reduce((a, b) => a + b) / arr.length;
    console.log(average)
}

Upvotes: 0

Views: 1057

Answers (2)

pilchard
pilchard

Reputation: 12919

Your question is unclear, but here is an example of accumulating multiple keys into a new object using reduce(). It also tracks the total number of each key encountered in case not all objects in the array have the same keys. The format you want your result array in is unclear, but I've shown an example of calculating the averages from the result of the reduce() call.

const arr = [
  {count1: 3, count2: 2}, 
  {count1: 4, count2: 10},
  {count1: 3, count3: 2}
  ];

const sumObj = arr.reduce((a, o) => (
  Object.entries(o).forEach(([k, v]) => (
    a[k] = {...a[k] ?? {sum: 0, total: 0}}
    , a[k]['sum'] += v
    , a[k]['total'] += 1)
    ), a), {});

console.log(sumObj);

const averageArr = Object.entries(sumObj).map(([k, {sum, total}]) => ({key: k, average: sum/total}));

console.log(averageArr);

Upvotes: 1

Andrew
Andrew

Reputation: 462

You can use map and reduce like so given multiple keys:

const exampleArray = [{swag: 3, count: 2}, {swag: 4, count: 10}];

// converting into array with only the key you want to use
const countArray = exampleArray.map((element) => element.count); // an array with just {count: value} elements in them.

// ... now reduce like normally

Upvotes: 1

Related Questions