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

94
Views
How to pick two random index from Array efficiently in javascript without duplicates?

I have an array of arrays and I need to pick 2 random and different combinaisions of (index1, index2)

Let me give an example

data = [["a", "b", "c", "d"], ["e", "g"], ["i", "j", "k"]]

I need to have (index1: 0 , index2: 2) and (index1: 2 , index2: 1)

How can I achieve that efficiently ?

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

0

First you can create one combination:

const i11 = Math.floor(Math.random() * data.length);
const i12 = Math.floor(Math.random() * data[i11].length);

Then you can check if the inner array has only one element. If it has only one element and it's the first combination, you should ignore it in the following steps:

const dataLength = data[i11].length > 1 ? data.length : data.length - 1;

Now you can generate the outer index for the second combination and adjust it:

let i21 = Math.floor(Math.random() * dataLength);
if (i21 >= i11 && data[i11].length === 1) ++i21;

Next you can check if the outer index of the first combination and the outer index of the second combination are the same and do the same adjustment to avoid duplicates:

const innerDataLength = i21 === i11 ? data[i21].length - 1 : data[i21].length;

Finally you can generate the second inner index and adjust it

let i22 = Math.floor(Math.random() * innerDataLength);
if (i21 === i11 && i22 >= i12) ++i22;

The whole code as a function with a test:

const data = [["a", "b", "c", "d"], ["e", "g"], ["i", "j", "k"]];

function combinations(data) {
  const i11 = Math.floor(Math.random() * data.length);
  const i12 = Math.floor(Math.random() * data[i11].length);

  const dataLength = data[i11].length > 1 ? data.length : data.length - 1;

  let i21 = Math.floor(Math.random() * dataLength);
  if (i21 >= i11 && data[i11].length === 1) ++i21;

  const innerDataLength = i21 === i11 ? data[i21].length - 1 : data[i21].length;
  let i22 = Math.floor(Math.random() * innerDataLength);
  if (i21 === i11 && i22 >= i12) ++i22;
  
  return [[i11, i12], [i21, i22]];
}

console.log(combinations(data));

for (let i = 0; i < 10000; ++i) {
    const [[i11, i12], [i21, i22]] = combinations(data);
    if (i11 === i21 && i12 == i22) console.log('Test failed!');
}

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!