JSNoob
JSNoob

Reputation: 5

How to find the sum and average of values in a map?

My goal is to add the numerical values in this map and divide them by the size of the map. The result is merely the numbers without being added. Here's how my code looks like as of the moment:

const problem2 = new Map();
problem2.set('Julie', 13);
problem2.set('Jojo', 10);
problem2.set('Polly', 10);
problem2.set('Jack', 10);
problem2.set('Bruce', 10);

let sum = "";
for (const value of problem2.values()){
   sum +=  parseInt (value, 10) +"\n";
};

sum; 

Upvotes: 0

Views: 1319

Answers (4)

GirkovArpa
GirkovArpa

Reputation: 4922

You can convert the Map to an Array so you can use the Array.reduce method.

const problem2 = new Map();
problem2.set('Julie', 13);
problem2.set('Jojo', 10);
problem2.set('Polly', 10);
problem2.set('Jack', 10);
problem2.set('Bruce', 10);

const { sum, avg } = [...problem2] // convert Map to Array
  .reduce((result, [, value]) => {
    result.sum += value;
    result.avg = result.sum / problem2.size;
    return result;
  }, { sum: 0, avg: 0 });

console.log({ sum, avg });
// { sum: 53, avg: 10.6 }

Upvotes: 0

Sascha A.
Sascha A.

Reputation: 4626

Go with foreach over the map and sum up. For avg divide through mapsize.

const problem2 = new Map();
problem2.set('Julie', 13);
problem2.set('Jojo', 10);
problem2.set('Polly', 10);
problem2.set('Jack', 10);
problem2.set('Bruce', 10);

let sum = 0;
problem2.forEach(value => sum += value);

console.log('Sum: ' + sum);
console.log('Average: ' + (sum / problem2.size));

Upvotes: 0

tsu
tsu

Reputation: 1261

You can use forEach and size property

let sum = 0;
problem2.forEach(value => sum += value); // value is problem

let average = sum / problem2.size

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89497

You should not be concatenating the string "\n" and sum should be initialized to 0 as you are working with numbers. The average is the sum divided by the number of values in the Map.

const problem2 = new Map();
problem2.set('Julie', 13);
problem2.set('Jojo', 10);
problem2.set('Polly', 10);
problem2.set('Jack', 10);
problem2.set('Bruce', 10);

let sum = 0;
for (const value of problem2.values()){
   sum += value;
};

console.log('Sum:',sum);
console.log('Average:', sum / problem2.size);

Upvotes: 0

Related Questions