This post will discuss how to get the sum of all map values in JavaScript.

To get the sum of all map values, we need to iterate over the values and add them up. Here are some of the possible functions:

1. Using Map.values() and Array.reduce() function

The Array.reduce() function applies a reducer function to each element of an array and returns a single value. The idea is to use the Map.values() function to get an iterator of the map’s values, and then use Array.from() or spread syntax () to convert it into an array. Then, we can use the Array.reduce() function to apply a function that accumulates the sum of the values. The following code illustrates this:

Download  Run Code

 
This is a concise and functional way to get the sum of all map values. If the map is an object literal that stores key-value pairs, where the values are numbers, we can use the Object.values() function to get an array of the object’s values, and then use the Array.reduce() function to apply a function that accumulates the sum of the values.

Download  Run Code

2. Using a loop

This is a simple and imperative way to get the sum of all map values. By using a for…of loop, we can iterate over the key-value pairs of the map and access the value of each pair. We can declare a sum variable and initialize it to zero, and then add each value to it inside the loop. The following code illustrates this:

Download  Run Code

3. Using Map.forEach() function

The Map.forEach() function executes a callback function for each key-value pair in the map. The callback function can access the value of the current pair and add it to a sum variable. The following code illustrates this:

Download  Run Code

That’s all about getting the sum of all map values in JavaScript.