Is there a Javascript function similar to the Python Counter function?

I am trying to change my program from Python to Javascript, and I was wondering if there is a JS function like the Counter function from the collection module in Python.

Syntax for counter

from collection import Counter list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a'] counter = Counter(list) print counter 

Output

 Counter({'a':5, 'b':3, 'c':2}) 
+6
source share
4 answers

You can use the Lo-Dash function countBy :

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

JSFiddle example

+4
source

DIY JavaScript solution:

 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

Update:

Alternative using constructor function:

 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
source

There is also pycollections.js that runs on Node and client side JS.

Example:

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

For those who want a clean JavaScript solution:

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

In this way:

 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} 
+1
source

Source: https://habr.com/ru/post/976626/


All Articles