aTubOfAdam
aTubOfAdam

Reputation: 91

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.

Upvotes: 1

Views: 840

Answers (2)

martti
martti

Reputation: 2075

You can use reduce to calculate the sum.

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

const mySum = myMap.values().reduce((previousValue, currentValue) => previousValue + currentValue[1], 0);

console.log(mySum);

Upvotes: 0

Reyno
Reyno

Reputation: 6525

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

Upvotes: 1

Related Questions