0
let arr=[1,2,3,4,5,5,5,6,6,6];
let map=new Map();
arr.forEach((n)=>{
    map.set(n,map.get(n)+1);
});
for(let [k,v] of map){
    console.log(k,v);
}

I want to count the frequency of the number in array,but it is wrong.When i debug in console,the value of map is Nan.

the result of code

Can i get some suggestions?

haobin liu
  • 13
  • 2
  • `map.set(n,(map.get(n)??0)+1);` - so the first get returns `0` not `undefined` - you can also use `||` instead of `??` – Jaromanda X Aug 31 '22 at 02:27

1 Answers1

2

Add map.get(n)||0, because the initial value for the map is undefined, not 0

let arr=[1,2,3,4,5,5,5,6,6,6];
let map=new Map();
arr.forEach((n)=>{
    map.set(n,(map.get(n)||0)+1);
});
for(let [k,v] of map){
    console.log(k,v);
}
Richard Henage
  • 1,758
  • 1
  • 3
  • 10
  • i didn't know `Map` exists in javascript. i always use `Object` to handle things. today i learned something new. – Layhout Aug 31 '22 at 02:38
  • you don't have answer this, but do you know any cases that `Map` is better to use than `Object`? example would be appreciated. thanks. – Layhout Aug 31 '22 at 02:44
  • 1
    They are very similar. This answers it partially: https://stackoverflow.com/a/18541990/16634738. – Richard Henage Aug 31 '22 at 02:48