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

145
Views
Choosing a random element from an array with weights

I'm currently trying to create a random weighted index picker.

My goal is to randomly pick an element from an array. However, its not just as simple as doing this. Certain elements have a boosted chance of winning. This can be viewed as a sort of lottery

The data structure is as follows:

const users = [
 {userId: 1, multiplier: 0},
 {userId: 2, multiplier: 25}
 {userId: 3, multiplier: 0}
 {userId: 4, multiplier: 25}
 {userId: 5, multiplier: 15}
 {userId: 6, multiplier: 30}
 {userId: 7, multiplier: 35}
 {userId: 8, multiplier: 2}
 {userId: 8, multiplier: 7}
]

Each element of the array counts as one entry. However, the multipliers allow the user to have a higher chance of winning.

A solution which I came up with was view the multipliers as number of tickets so if a user had a multiplier of 25 then they would have 25 tickets.

However, this is very inefficient because when there are 10s of thousands of entries with many multipliers the array size grows at an incredible rate.

I'm not sure how I can make this more efficient.

My solution can be viewed here:

const users = [
 {userId: 1, multiplier: 0},
 {userId: 2, multiplier: 25}
 {userId: 3, multiplier: 0}
 {userId: 4, multiplier: 25}
 {userId: 5, multiplier: 15}
 {userId: 6, multiplier: 30}
 {userId: 7, multiplier: 35}
 {userId: 8, multiplier: 2}
 {userId: 8, multiplier: 7}
]

const potentialWinners = []

users.map((user) => {
    for(let i=0; i < user.multiplier; i++) {
        potentialWinners.push(user.userId)
    }
})

Other solutions which I have viewed seemed quite complicated and I am not great at Math so I had a hard time understanding what was happening.

They also all seem to work based off of percentages, and mine doesn't I'm not entirely sure how I can rework the multiplier system to take into account a multiplied chance of winning.

about 4 years ago · Juan Pablo Isaza
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!