benshope
benshope

Reputation: 3024

Create JavaScript Array of Random Ints

In Python, if I want a random array of integers up to a certain size, I do:

random_array = numpy.random.randint(20, size=10)

In Javascript, I can not figure out a good one-line way to do this. I tried using UnderscoreJS:

random_array = _.sample(_.range(20), 10);

I also tried using Javascript 1.7 array comprehensions plus UnderscoreJS:

random_array = [Math.floor(Math.random() * 20) for (x of _.range(10))];

The first one creates only unique values, the second way does not seem to work at all. Any ideas? What is the best way to do this?

Upvotes: 1

Views: 1429

Answers (2)

Tim
Tim

Reputation: 491

If you want just a (fairly long) javascript one-liner without underscore/other libraries:

var random_array = function (){var a=[]; for(var i=0;i<10;i++){a[i]=Math.floor(Math.random()*20);};return a;}();

This is in answer to "any ideas?" I'm not sure if it's an answer to "what is the best way?"

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816522

Looks like _.times and _.random would be useful:

var random_array = _.times(10, _.random.bind(_, 0, 19));

You could also create a tiny helper function around _.random:

function randomIntFactory(max) {
    // _.random's max value is *inclusive* (unlike the Python version)
    // so we subtract one
    return _.random.bind(_, 0, max - 1);
}

var random_array = _.times(10, randomIntFactory(20));

Note: Instead of native .bind you can also use underscore's _.bind.

Upvotes: 5

Related Questions