Search code examples
javascriptmaps

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.

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);