Get the Sum of all Values in a Map using JavaScript


When working with a Map in JavaScript, you might need to calculate the sum of all values. In this guide, lets explore the various ways to do so:


Using a For…of Loop

One straightforward way to calculate the sum of Map values is by using a for…of loop. This approach iterates through each entry in the Map, allowing us to accumulate the sum.

JavaScript
const scores = new Map([
  ['Alice', 95],
  ['Bob', 88],
  ['Charlie', 92],
]);

let sum = 0;

for (const value of scores.values()) {
  sum += value;
}

console.log(sum); // Output: 275

In this example, we initialize a Map called scores with student names as keys and their respective scores as values. The for…of loop iterates through the values, adding each score to the sum variable.

Using Map.forEach()

Another method involves using the forEach() method provided by the Map object. This approach offers a cleaner and more functional style of iterating over Map entries.

JavaScript
const scores = new Map([
  ['Alice', 95],
  ['Bob', 88],
  ['Charlie', 92],
]);

let sum = 0;

scores.forEach((value) => {
  sum += value;
});

console.log(sum); // Output: 275

The forEach() method simplifies the iteration process, and the provided callback function handles the summation logic.

Using Array.from() and Reduce

We can convert Map values into an array using Array.from() and then apply the reduce() method to calculate the sum.

JavaScript
const scores = new Map([
  ['Alice', 95],
  ['Bob', 88],
  ['Charlie', 92],
]);

const sum = Array.from(scores.values()).reduce((acc, value) => acc + value, 0);

console.log(sum); // Output: 275

Here, Array.from(scores.values()) converts the Map values to an array, and reduce() accumulates the sum. The 0 passed as the second argument to reduce() initializes the accumulator (acc) to zero.


🧪Practice Coding Problem: Calculate Party Sum

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

You are the party organizer, and each guest has a unique value to bring to the event. Write a function calculatePartySum to find the sum of all these values stored in a Map.

JavaScript
/**
 * Calculate Party Sum
 * @param {Map} partyMap - The Map of guests with their unique values
 * @returns {number} - The sum of all guest values at the party
 */
function calculatePartySum(partyMap) {
  // > > > 👉 Write code here 👈 < < <
}

// Example Usage:
const partyContributions = new Map([
  ['Alice', 30],
  ['Bob', 20],
  ['Charlie', 25],
  ['Diana', 35]
]);

const totalSum = calculatePartySum(partyContributions);
console.log(totalSum); // Expected output: 110
Please attempt before seeing the Answer:
JavaScript
function calculatePartySum(partyMap) {
  let sum = 0;
  partyMap.forEach(value => {
    sum += value;
  });
  return sum;
}

The calculatePartySum function ensures you know the total value each guest brings to the party.


To sum it up, now you can get the total value of any Map. 🗺💲 😁

Keep coding🚀!

Scroll to Top