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);
CodePudding user response:
Your final loop is accessing listaArray[i][1]
without first checking that i
is still less than the length of that array. So add i < listaArray.length
as a condition in that while
loop.
Not your question, but:
- There is no reason to treat a separate case in the
if
that precedes that loop. Just remove that part: thewhile
loop should take care of it. - Don't use
.map
when you just want to iterate and not really map. Afor..of
loop would be appropriate here. - As your input seems to consist of numbers, you need to make the conversion from string back to number again. Object keys are never of the number type.
Your code could look like this (still with the while
loop):
function calcularModa(listaUser) {
const lista = listaUser;
const listaCount = {};
for (let elemento of lista) {
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 i = 1;
while (i < listaArray.length && listaArray[0][1] == listaArray[i][1]) {
i ;
}
return listaArray.slice(0, i).map(([key]) => key).map(Number);
}
let moda = calcularModa([1,2,4,3,2,3,5]);
console.log(moda);