find the sum of all values in a map in javascript

To find the sum of all values in a map in JavaScript, you can use the reduce() function along with an iteration over the values() of the map. Here's an example code block:

index.tsx
const myMap = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3]
])

const sum = [...myMap.values()].reduce((a, b) => a + b, 0)

console.log(sum) // output: 6
153 chars
10 lines

In this example, we first create a Map object myMap with three key-value pairs. Then, we use the spread operator along with myMap.values() to get an array of all values in the map. We then pass this array to the reduce() function, which iteratively sums up all elements of the array, starting with an initial value of 0. The reduce() function returns the final sum. Finally, we log the sum to the console.

gistlibby LogSnag