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

108
Views
Compress Javascript Options Array

I've inherited a website and am trying to compress some badly written script. One particular section updates the options in a select field based on other selections. It takes the numeric values from two other select fields in order to update the number of possible options on a third field.

Here is the code in question:

    var value = parseInt(first_value) + parseInt(second_value);
    if(value == 1){
        var newOptions = {"0": "0", "1": "1",};
    } else if(value == 2){
        var newOptions = {"0": "0", "1": "1", "2": "2",};
    } else if(value == 3){
        var newOptions = {"0": "0", "1": "1", "2": "2", "3": "3",};
    } else if(value == 4){
        var newOptions = {"0": "0", "1": "1", "2": "2", "3": "3",  "4": "4",};
    } else if(value == 5){
        var newOptions = {"0": "0", "1": "1", "2": "2", "3": "3",  "4": "4", "5": "5",};
    }

It goes on like this all the way up to value == 30 so it ends up being a lot of code and I am convinced there is a way to reduce it down.

I've tried a few solutions myself which failed entirely, so thought I'd turn to the community to see if anyone has any ideas?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Here's a quick and easy way. By setting the iterator x to -1, we can use ++x in the while loop. Explicit Number casting (+val) is probably overkill, but handy if the value for val is coming from an input or other HTML element

const getOptions = val => {
  let base = {}, x = -1;
  while (++x <= +val) base[x] = x.toString();
  return base
}

newOptions = getOptions(5);
console.log(newOptions)

about 4 years ago · Juan Pablo Isaza Report

0

Something like this?

   const foo =(value) => {
    let newOptions={0:'0'}
    for (let i = 1; i < value+1; i++) newOptions[i]=i.toString()   
    return newOptions
   }

   console.log(foo(30))

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!