Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get the sum of all values in a map with multiple values?

PROBLEM

I have a map that looks like this:

const myMap= new Map();

myMap.set("MapItem1", [1, 4.5]);
myMap.set("MapItem2", [0, 3]);
myMap.set("MapItem3", [1, 10]);
myMap.set("MapItem4", [1, 1]);

As you can see, this map has 1 key, and an array with 2 values. What I’m trying to do is get the sum of all the second values.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Solution Attempt

I tried to write a function that looks like this:

 function sumArray(map[k,[v, v1]]) {
  for (let i = 0; i < map.length; i += 1) {
    sum += map[v1];
  }
  return sum;
  }

My thought is to use a function which takes a map object that matches the one above and iterate through it, summing the second value parameter as I go.

This simply hasn’t worked for me, returning nothing at all. Would appreciate any help seeing flaws in my logic, or advice for different solutions.

>Solution :

An easy solution would be to loop over the values of the map and then sum them up one by one.

const myMap= new Map();

myMap.set("MapItem1", [1, 4.5]);
myMap.set("MapItem2", [0, 3]);
myMap.set("MapItem3", [1, 10]);
myMap.set("MapItem4", [1, 1]);

let sum = 0;
for(const arr of myMap.values()) {
  sum += arr[1];
}
console.log(sum);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading