Count the number of times a same value appears in a javascript array

前端 未结 8 2101
执笔经年
执笔经年 2020-12-14 07:27

I would like to know if there is a native javascript code that does the same thing as this:

function f(array,value){
    var n = 0;
    for(i = 0; i < arr         


        
8条回答
  •  醉梦人生
    2020-12-14 08:18

    You can also use forEach

    let countObj = {};
    let arr = [1,2,3,1,2,3,4];
    
    let countFunc = keys => {
      countObj[keys] = ++countObj[keys] || 1;
    }
    
    arr.forEach(countFunc);
    
    // {1: 2, 2: 2, 3: 2, 4: 1}
    

提交回复
热议问题