1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS
1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS

Get the Sum of all Values in a Map using JavaScript

ReadTime: 4 minutes

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
Using a for of loop to calculate the sum of Map values

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
Using a for each loop to calculate the sum of Map values

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
Using a Array.from() and reduce() to calculate the sum of Map values

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.

Problem

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
Code for Problem Statement

Please attempt before seeing the Answer:

Solution
javascript
function calculatePartySum(partyMap) {
  let sum = 0;
  partyMap.forEach(value => {
      sum += value;
  });
  return sum;
}
Solution Code

Explanation:

  • 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🚀!

Contact

Feel free to reach out!