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

时间:2014-10-11 23:17:43

标签: 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

输出

Counter({'a':5, 'b':3, 'c':2})

6 个答案:

答案 0 :(得分:5)

您可以使用Lo-Dash的countBy功能:

var list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a'];
console.log(_.countBy(list));

JSFiddle example

答案 1 :(得分:4)

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

JSFiddle example

<强>更新

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

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

JSFiddle example

答案 2 :(得分:1)

还有pycollections.js,它适用于Node和客户端JS。

示例:

var collections = require('pycollections');
var counter = new collections.Counter([true, true, 'true', 1, 1, 1]);
counter.mostCommon(); // logs [[1, 3], [true, 2], ['true', 1]] 

答案 3 :(得分:1)

对于那些想要纯JavaScript解决方案的人:

function countBy (data, keyGetter) {
  var keyResolver = {
    'function': function (d) { return keyGetter(d); },
    'string': function(d) { return d[keyGetter]; },
    'undefined': function (d) { return d; }
  };

  var result = {};

  data.forEach(function (d) {
    var keyGetterType = typeof keyGetter;
    var key = keyResolver[keyGetterType](d);

    if (result.hasOwnProperty(key)) {
      result[key] += 1;
    } else {
      result[key] = 1;
    }
  });

  return result;
}

因此:

list1 = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a'];
console.log(countBy(list1));  // {'a':5, 'b':3, 'c':2}

list2 = ['abc', 'aa', 'b3', 'abcd', 'cd'];
console.log(countBy(list2, 'length'));  // {2: 3, 3: 1, 4: 1}

list3 = [1.2, 7.8, 1.9];
console.log(countBy(list3, Math.floor));  // {1: 2, 7: 1}

答案 4 :(得分:1)

我知道我来晚了,但是如果有人在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 }

具有回调功能和上下文绑定的更高级示例

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

const counter = (list, fun, context) => {
  fun = context ? fun.bind(fun) : 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 }

答案 5 :(得分:0)

这是一个简单易读的解决方案:

 const word1 = "tangram"
    const dict1 = {}
    for (let char of word1){
     console.log(char)
     if (dict1[char]){
       dict1[char] += 1
       }else{
     dict1[char]= 1
     }
    }

enter image description here

enter image description here