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).
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
– Costamilam