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

265
Views
How to generate a random array in JS?

I need to generate a different array each time in JS , where it's length should be exact 16 elements , each element should be between 0 to 7 , and each element should occur exactly twice. for eg. [0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7] or [0,1,2,3,4,5,6,7,7,6,5,4,3,2,1,0]

I need a function that will generate different array each time.

let sequence=[0,1,2,3,4,5,6,7]
let seq1=[0,1,2,3,4,5,6,7]
let seq2=[0,1,2,3,4,5,6,7]
let arr1=[]
let arr2=[]
let arr3

function generateArray(arr,seq){
    for(let i=0;i<8;i++){
        let numb=Math.trunc(Math.random()*(seq.length))
        arr.push(seq[numb])
        seq.splice(numb,1)
    }
}

generateArray(arr1,seq1)
generateArray(arr2,seq2)

arr3=[...arr1,...arr2]
console.log(arr3)

I've used the above function , but the drawback is that it firsts generates randomly all the numbers from 0 to 7 , and then does the same again.

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

0

There's two functions:

  • xArray(num) Instantiates a new Array and fills it with consecutive numbers to the given length

  • shuffle(arr) It shuffles any type of Array using the Fisher–Yates shuffle algorithm

const xArray = x => [...new Array(x)].map((_, i) => i);

const shuffle = array => {
  let qty = array.length, temp, i;
  while (qty) {
    i = Math.floor(Math.random() * qty--);
    temp = array[qty];
    array[qty] = array[i];
    array[i] = temp;
  }
  return array;
};

let a = shuffle(xArray(8));
let b = shuffle(xArray(8));

console.log([...a, ...b]);

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!