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

202
Views
generate 4 unique random number in arr?

If I want 4 random number in an array [num1, num2, num3, num4], I can't do

function getRandomFloat(min, max) {
  return Math.random() * (max - min) + min;
}

const arr = [getRandomFloat(1,10), getRandomFloat(1,10), getRandomFloat(1,10), getRandomFloat(1,10)]

because I'll have duplicated value. Is there any way or library that allow me to generate a unique set of randomed number?

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

0

You can declare the array as empty and then continue adding values to it until it has 4 numbers. You can also avoid duplicates by using if condition.

function getRandomFloat(min, max) {
      return Math.random() * (max - min) + min;
    }
    
    var arr=[];
    var min=1, max=10;
    while (arr.length != 4)  // executes loop till length of array is 4
    {
        var i = getRandomFloat(min, max);
        // checking if number already exists in array
        if (arr.includes(i))
        {
            continue;
        }
        arr.push(i);
    }
about 4 years ago · Juan Pablo Isaza Report

0

This is efficient method to achieve this. You can use Set to get the random unique numbers in an array

You can even add a check if unique numbers are possible or not as

  if (max - min < n) return "Not possible";

function getRandomNumbers(n, min = 0, max = 0) {
  const set = new Set();
  while (set.size !== n) {
    set.add(Math.random() * (max - min) + min);
  }
  return [...set];
}

console.log(getRandomNumbers(4, 1, 10));

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!