Count words in Array

Asked

Viewed 456 times

2

How do I count the amount of words that appear within an array. Example:

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

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

I want a logic that does it dynamically independent of names.

2 answers

4


I’ve needed something like this before; this is not the easiest way to understand but it was the most "beautiful" I have already used (found in this answer of OS):

var totais = {};
array_palavras.forEach(function(x) { totais[x] = (totais[x] || 0) + 1; });
  • 1

    Thanks worked out !!!!!

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 for the accumulation of totals is {} passed as the second parameter of reduce, which makes this solution need not have a previously created empty object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.