Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!