2014-10-11 14 views
6

Sto tentando di cambiare un mio programma da Python a Javascript e mi chiedevo se esistesse una funzione JS come la funzione Counter dal modulo collections in Python.Esiste una funzione Javascript simile alla funzione Contatore Python?

sintassi per Counter

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

uscita

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

Vedi http://stackoverflow.com/a/12873271/2055998 –

risposta

4
countBy funzione di

È possibile utilizzare Lo-Dash:

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

JSFiddle example

+0

'console.log (_. CountBy ([4,6,5,8,8,9,7,8]))' produce '" _ _ non è definito " ' – Musixauce3000

+1

È necessario includere la soluzione lodash lib –

1

C'è anche pycollections.js, che funziona su Node e in JS lato client.

Esempio:

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

Per coloro che desiderano una soluzione di pura 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; 
} 

Pertanto:

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

fai da te JavaScript soluzione:

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

Aggiornamento:

alternativa che utilizza un costruttore funzione:

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

+0

buona! Mi piace – ospider

+0

Grazie! Ho aggiunto un'alternativa che utilizza una funzione di costruzione e la parola chiave 'new'. – nitsas

Problemi correlati