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

377
Views
JavaScript: How can you select random elements from an array without allowing duplicates?

I am looking to randomly select a number from this array WITHOUT duplicates. There can only be two possibilities for each number as shown in the array, select up to a maximum of 6. This works to select a random number but allows duplicates...

const smallNums = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10];

const randomSmallNumArr = smallNums[Math.floor(Math.random() * smallNums.length)];

When using the splice() method, each time I generate a number based on a random index, it's removed but shows up again in the array the next time a random is generated

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

0

Use a Set to get the unique items in the array.

const smallNums = [...new Set([1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10])]

const randomSmallNumArr = smallNums[Math.floor(Math.random() * smallNums.length)];
console.log(randomSmallNumArr)

about 4 years ago · Juan Pablo Isaza Report

0

If I understand your requirement clearly, You want to generate a non-repeating random numbers from an array of numbers ? If Yes, I added a solution below.

// Input array
const arr = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10];

// Remove duplicate elements from an array
let uniqueElementsArr = [...new Set(arr)];

// Find out random number from an array
const randomNum = uniqueElementsArr[Math.floor(Math.random()*uniqueElementsArr.length)];

// removing the random number from the existing array so that it should not be replicate.
if (uniqueElementsArr.indexOf(randomNum) !== -1) {
    uniqueElementsArr.splice(uniqueElementsArr.indexOf(randomNum), 1)
}

console.log(randomNum);

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!