array_count_values for JavaScript instead

前端 未结 6 1580
情歌与酒
情歌与酒 2020-12-10 20:04

I have the following PHP-script, now I need to do the same thing in JavaScript. Is there a function in JavaScript that works similar to the PHP function, I have been searchi

6条回答
  •  我在风中等你
    2020-12-10 20:44

    How about this:

    function arrayCountValues (arr) {
        var v, freqs = {};
    
        // for each v in the array increment the frequency count in the table
        for (var i = arr.length; i--; ) { 
            v = arr[i];
            if (freqs[v]) freqs[v] += 1;
            else freqs[v] = 1;
        }
    
        // return the frequency table
        return freqs;
    }
    

提交回复
热议问题