Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

140
Vistas
Trying To Display Number Of times each option is selected using an array

I am trying to write a code which displays the sum of number of times each option is selected using an array

However whenever I run this code the array resets all elements to zero after running the code the second time

let arr = [0,0,0,0]

const poll = { 
    registerNewAnswer: function(a)
    {
        return prompt(`
            Which is your favourite Movie?
            0: Toy Story
            1: Star Wars
            2: Fast & Furious
            3: Final Destination
            (Write option number)
        `);
    }
}

let b = poll.registerNewAnswer(); 
console.log(b);
for(let [i,j] of arr.entries())
{
    if (i==b)
    {
        arr[i]=(arr[i]+1);
    };
}
console.log(...arr);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You need to store the entries somewhere, otherwise your first line will always reset arr to zero. I suggest localStorage for this example. Could also be a call out to an API for database storage.

In the code below- it first checks for the existence of the localStorage.arr.

Then, if it is null, it creates an empty array and saves it for next time.

Also, b isn't necessary, you can just add it to the array with arr[].

let arr = localStorage.getItem('arr');
if (!arr) {
    arr = [];
    localStorage.setItem('arr', arr);
}

const poll = { 
    registerNewAnswer: function()
    {
        return prompt(`
            Which is your favourite Movie?
            0: Toy Story
            1: Star Wars
            2: Fast & Furious
            3: Final Destination
            (Write option number)`);
    }
}

arr.push(poll.registerNewAnswer()); 
console.log(poll.registerNewAnswer);
for(let [i,j] of arr.entries())
{
    if (i==b)
    {
    arr[i]=(arr[i]+1);
    };
}
console.log(...arr);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda