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

219
Views
Generating a randomize value from an array based on the array element index position within a loop in JavaScript

I have an array of fixed or randomized distance values, multiplied by the scale of a map, mapScale. The randomized values can be generated using function randomNum(num1, num2).

I am looking to assign to variable distance a new value, for each iteration within a loop, using a pre-determined distances array index position. The array index position value should remain the same for each iteration within the loop (ex: 6), but the distance value should change for each iteration if the array element is a randomized number for the specified index position.

Please note that if a "randomization" index position is specified, I do want to get a new randomized number for each iteration (ex: 6.22, 7.08, 9.45, etc.) and not simply a constant pre-determined one (ex: 7.84).

The following code works, but calling randomNum for each iteration is probably not optimal, especially since we already know the index position of the element we are looking to retrieve. Please also note that the number of iterations, n, varies from about 500 to roughly 10,000.

var indexPosition = findIndexPosition(...)

for (let i = 0; i <= n; i++){   

   var distances = [
      mapscale * 0.25,
      mapscale * 0.75,
      mapscale * 1,
      mapscale * 1.5,
      mapscale * 2,
      mapscale * randomNum(3, 5),
      mapscale * randomNum(6, 10),
      mapscale * randomNum(15, 50),
      mapscale * randomNum(100, 500),
      mapscale * randomNum(1000, 2500),
   ];

   var distance = distances[indexPosition]

   [...]
 }      

I would like to find the most elegant solution (optimal speed / number of line balance) to achieve the desired behavior. I am open to using a switch statement, a function, object, etc., as long as the code remains concise and the performance is optimized.

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

0

How about this:

var indexPosition = findIndexPosition(...)

const distances = [
   () => mapscale * 0.25,
   ...
   () => mapscale * randomNum(1000, 2500)
];

for (let i = 0; i <= n; i++){   
   var distance = distances[indexPosition]()
   ...
}
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!