Home > Software design >  How to get sum of all values in ES6 Node JS Map
How to get sum of all values in ES6 Node JS Map

Time:11-25

My code is not able to sum of all values using Node JS. Can someone help to fix it?

Error at VS code is TypeError: undefined is not a function

let addInput = new Map( 
  {"key1":10},
  {"key2":5},
  {"key3":7},
  {"key4":17}
);

let sum = 0;

addInput.forEach((v) => {
  sum  = v;
});

console.log(sum);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You have to create a Map of key-value, You can use flatMap here:

const arr = [{ key1: 10 }, { key2: 5 }, { key3: 7 }, { key4: 17 }];
let addInput = new Map(arr.flatMap((o) => Object.entries(o)));

const arr = [{ key1: 10 }, { key2: 5 }, { key3: 7 }, { key4: 17 }];
let addInput = new Map(arr.flatMap((o) => Object.entries(o)));

let sum = 0;
addInput.forEach((v) => {
  sum  = v;
});

console.log(sum);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I'd prefer to use for..of loop here

const arr = [{ key1: 10 }, { key2: 5 }, { key3: 7 }, { key4: 17 }];
let addInput = new Map(arr.flatMap((o) => Object.entries(o)));

let sum = 0;
for (let [, v] of addInput) sum  = v;

console.log(sum);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You could set values for a new Map using set method:

 let addInput = new Map();
addInput.set("key1", 10);
addInput.set("key2", 5);
addInput.set("key3", 7);
addInput.set("key4", 12);
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related