Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda