I've been trying to find a solution, but I don't know what's wrong here.
The code below results in this error on the line with the while
statement:
Uncaught TypeError: Cannot read properties of undefined (reading '1')
I want to make a while loop, such that while two elements in an array are the same, that value is pushed in the result array until the compared elements are different:
function calcularModa(listaUser){
const lista = listaUser;
const listaCount = {};
lista.map(
function (elemento){
if (listaCount[elemento]){
listaCount[elemento] += 1;
} else{
listaCount[elemento] = 1;
}
}
);
const listaArray = Object.entries(listaCount).sort(
function (valorAcumulado, nuevoValor) {
return nuevoValor[1] - valorAcumulado[1];
}
);
let moda;
if (listaArray[0][1] != listaArray[1][1]){
moda = listaArray[0];
return moda;
}
moda = [listaArray[0]]
let i = 1;
while(listaArray[0][1] == listaArray[i][1])
{
moda.push(listaArray[i])
i++;
}
return moda;
}
let moda = calcularModa([1,1,2,2,3,3]);
console.log(moda);