Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda