Melanie P.
Melanie P.

Reputation: 53

Random repeating elements in an array

I'm using _.sample in underscore.js to pull random elements from an array.

I have less elements in the source list than the amount I want to sample, but it's maxing out at 4 (the length of the source).

What are some other options for returning 17 random elements (with repeats, obviously) from 4 options in an array? I'm seeing a lot on removing the repeats but can't figure out what allows for them to repeat.

let dots = _.sample([component 1, component 2, component 3, component 4], 17);

Upvotes: 1

Views: 130

Answers (2)

Rodrigo Rodrigues
Rodrigo Rodrigues

Reputation: 8556

You just need to get random numbers from 0 to 3 (you can use underscores's _.random), and use them as index to get elements from you components array.

var components = [component1, component2, component3, component4]
var dots = []
for (var i = 0; i < 17; ++i) dots.push(components[_.random(3)]);

Upvotes: 2

yang zhou
yang zhou

Reputation: 318

let dots = _.sample(Array.from({length: 5}).fill([component 1, component 2, component 3, component 4]).flat(), 17)

Upvotes: 0

Related Questions