Home > Enterprise >  Slimming down nested array Javascript
Slimming down nested array Javascript

Time:02-05

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  
}

CodePudding user response:

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

CodePudding user response:

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;
}
  •  Tags:  
  • Related