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

138
Views
Slimming down nested array Javascript

I've been trying to port over the functionality of

random.sample(range(0, 6), 2)

to javascript from python using this function:

function randomIntFromInterval(range, n) {
  var sample = [];
  for(var i=0; i<n; i++) {
    sample.push(range.splice(Math.random()*range.length,1));
  }

  return sample;
}

However I am getting this result:

[[[2], [3]], [[1], [2]], [[6], [1]], [[4], [3]], [[2], [1]], [[6], [2]], [[0], [2]], [[1], [6]], [[1], [3]], [[6], [5]]]`

Instead of something like this:

[[2, 3], [1, 2], [6, 1], [4, 3], [2, 1], [6, 2], [0, 2], [1, 6], [1, 3], [6, 5]]

Any Tips?

EDIT: this is the code im using to call the function

var randomizedOff = []
while (z < 10){
randx = randomIntFromInterval([0,1,2,3,4,5,6],2)
  randomizedOff.push(randx)
  z++
}

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

0

This is happening because you are using splice which always returns an array use [0] to get the element

function randomIntFromInterval(range, n) {
  var sample = [];
  for(var i=0; i<n; i++) {
    sample.push(range.splice(Math.floor(Math.random() * range.length), 1)[0]);
  }
  return sample;
}

It is unclear if the example output is multiple calls of the function in an array or just one

about 4 years ago · Juan Pablo Isaza Report

0

slice() returns an array of all the elements that were removed from the array. So if you remove one element, you get an array with one element.

You can simply index it with [0] to extract the element from the array.

function randomIntFromInterval(range, n) {
  var sample = [];
  for(var i=0; i<n; i++) {
    sample.push(range.splice(Math.random()*range.length,1)[0]);
  }

  return sample;
}
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!