Would you like to know how to build a function that counts repeated numeric values in an array?

Asked

Viewed 63 times

1

How to count the most repeated value ?. I tried it in this format and it doesn’t work

let array = [2,3,4,5,6,7,8,9,2,2,3,2,1,3]
let contador = 0
    for(i=0 ;i <= array.length ; i++){
        if(array[i] == array[i + 1]){
            contador += 1
        }
    }

  • You need to save, in addition to how many times it repeats, the number in question, moreover, this way you only check if the next number is equal to the previous one, and not if the array has some number equal to the one you want

2 answers

4

First you need to save how many times each element occurs. For this you can use an object whose keys are the array numbers, and the respective values are the number of occurrences.

Then you have to find the highest value between occurrences.

And finally, you scroll through the elements of the object and only print those whose amount of occurrences is equal to the highest value (after all, it may be tied, so I did it in a way that shows all the most frequent):

// os números 2 e 3 ocorrem 4 vezes cada (ambos sáo os mais frequentes)
let array = [2, 3, 4, 5, 6, 7, 8, 9, 2, 2, 3, 2, 1, 3, 1, 3, 5, 100, 8];

// contar quantas vezes cada elemento ocorre e guardar em "cont"
let cont = {};
for (const n of array) {
    // se o número já tinha uma contagem, atualiza somando 1
    if (cont.hasOwnProperty(n)) {
        cont[n] += 1;
    } else cont[n] = 1; // senão, inicia a contagem do número com 1
}

// encontrar a maior ocorrência
let max = Math.max.apply(null, Object.values(cont));

// encontrar todos os valores que ocorrem "max" vezes
console.log(`Elementos mais frequentes, ocorrem ${max} vezes:`);
for (const n of Object.keys(cont)) {
    if (cont[n] == max) console.log(n);
}

First I created the object cont, that in the example above, after the first for, will look like this:

{ '1': 2, '2': 4, '3': 4, '4': 1, '5': 2, '6': 1, '7': 1, '8': 2, '9': 1, '100': 1 }

That is, the keys are the array numbers, and the values are the amount of times each occurs.

Then I use Math.max to find the highest value between occurrences (using Object.values to obtain only the values of cont). But how Object.values returns an array and Math.max takes multiple arguments (not an array of values), I use apply so that the array elements returned by Object.values are passed as arguments to Math.max.

Having the most occurrences, I go through cont and I only print the numbers that occurred this amount of times (since it may have more than one).

0

dados = ['1', '2', '3', '3', '1']
var contabiliza_dados = { };

for (var i = 0, j = quantidade_itens; i < j; i++) {
   contabiliza_dados[dados[i]] = (contabiliza_dados[dados[i]] || 0) + 1;
}

console.log(contabiliza_dados);

Browser other questions tagged

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