是否有类似于Python Counter函数的Javascript函数?

mic*_*pri 7 javascript python

我正在尝试将我的程序从Python更改为Javascript,我想知道是否有一个JS函数,比如Python中的collections模块中的Counter函数.

计数器的语法

from collection import Counter
list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a']
counter = Counter(list)
print counter
Run Code Online (Sandbox Code Playgroud)

产量

Counter({'a':5, 'b':3, 'c':2})
Run Code Online (Sandbox Code Playgroud)

nit*_*sas 6

DIY JavaScript解决方案:

var list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a'];

function Counter(array) {
  var count = {};
  array.forEach(val => count[val] = (count[val] || 0) + 1);
  return count;
}

console.log(Counter(list));
Run Code Online (Sandbox Code Playgroud)

JSFiddle示例

更新:

使用构造函数的替代方法:

var list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a'];

function Counter(array) {
  array.forEach(val => this[val] = (this[val] || 0) + 1);
}

console.log(new Counter(list));
Run Code Online (Sandbox Code Playgroud)

JSFiddle示例


Seb*_*n S 5

你可以使用Lo-Dash的countBy函数:

var list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a'];
console.log(_.countBy(list));
Run Code Online (Sandbox Code Playgroud)

JSFiddle示例

  • 您需要包括lodash库 (2认同)

row*_*adz 5

我知道我迟到了,但如果有人在 2020 年看到这个,你可以使用reduce 来做到这一点,例如:

const counter = (list) => {
  return list.reduce(
    (prev, curr) => ({
      ...prev,
      [curr]: 1 + (prev[curr] || 0),
    }),
    {}
  );
};

console.log(counter([1, 2, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 1, 0]));
// output -> { '0': 1, '1': 6, '2': 2, '3': 1, '4': 1, '5': 1, '6': 1, '7': 1 }
Run Code Online (Sandbox Code Playgroud)

带有回调函数和上下文绑定的更高级示例

const data = [1, 2, 3, 4, 5];

const counter = (list, fun, context) => {
  fun = context ? fun.bind(context) : fun;
  return list.reduce((prev, curr) => {
    const key = fun(curr);
    return {
      ...prev,
      [key]: 1 + (prev[key] || 0),
    };
  }, {});
};


console.log(counter(data, (num) => (num % 2 == 0 ? 'even' : 'odd')));
// output -> { odd: 3, even: 2 }
Run Code Online (Sandbox Code Playgroud)