Home > Enterprise >  I want to count the frequency of the number in array,but it's wrong when i use javascript Map()
I want to count the frequency of the number in array,but it's wrong when i use javascript Map()

Time:08-31

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?

CodePudding user response:

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

  • Related