Count words in Array

2

How do I count the number of words that appeared within an array. Example:

['thiago','carlos','pereira','thiago']

"thiago" appeared 2 times, "carlos" 1 and "pereira" 1.

I want a logic that does this dynamically regardless of the names.

    
asked by anonymous 28.02.2018 / 19:02

2 answers

4

I've needed something like this; This is not the easiest way to understand but it was the "pretty" I've ever used (found in this answer of the OS):

var totais = {};
array_palavras.forEach(function(x) { totais[x] = (totais[x] || 0) + 1; });
    
28.02.2018 / 19:09
2

Another possible solution would be to use reduce . It is not as compact as a line, but ends up being simple and even similar:

let nomes = ['thiago','carlos','pereira','thiago'];

const totais = nomes.reduce((acumulador, elemento) => {
    acumulador[elemento] = (acumulador[elemento] || 0) + 1;
    return acumulador;
}, {});

console.log(totais);

Note that the object used to accumulate totals is {} passed as second parameter of reduce , which means that this solution does not need to have an empty object created previously.

    
28.02.2018 / 21:00