Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing values in JavaScript Map object

Tags:

javascript

I have given array of strings and I'd want to make map which will have those strings as keys and values will be how many times each string is present in the array. The problem is I can't really increment value, which was once added to the map. It's my code:

for(let str of data) {
    if(map.has(str)) map[str] = map.get(str) + 1;
    else map.set(str, 1);
}

But it doesn't work as intended. I tried map[str]++ etc. but nothing worked for me...

like image 201
hnwoh Avatar asked Jul 14 '26 19:07

hnwoh


1 Answers

You're almost there:

for(const str of data) {
    if(map.has(str)) map.set(str, map.get(str) + 1);
    else map.set(str, 1);
}
like image 103
Evert Avatar answered Jul 16 '26 09:07

Evert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!