array_count_values for JavaScript instead

前端 未结 6 1575
情歌与酒
情歌与酒 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:50

    Another elegant solution would be to use Array.prototype.reduce. Given:

    var arr = new Array("apple","banana","apple","orange","banana","apple");
    

    You can just run reduce on it:

    var groups = 
      arr.reduce(function(acc,e){acc[e] = (e in acc ? acc[e]+1 : 1); return acc}, {});
    

    Finally you can check the result:

    groups['apple'];
    groups['banana'];
    

    In the sample above reduce takes two parameters:

    1. a function (anonymous here) taking an accumulator (initialized from the second argument of reduce), and the current array element
    2. the initial value of the accumulator

    Whatever the function returns, it will be used as the accumulator value in the next call.

    From a type perspective, whatever the type of the array elements, the type of the accumulator must match the type of the second argument of reduce (initial value), and the type of the return value of the anonymous function. This will also be the type of the return value of reduce.

提交回复
热议问题