ted
ted

Reputation: 14734

How to randomize (shuffle) a Javascript Set

I want to merge 3 sets and then itereate over their union, but I'd like this union to be randomized.

If I do:

const a = new Set([1,2,3]);
const b = new Set([10,20,30]);
const c = new Set([100,200,300]);
const d = new Set([...a, ...b, ...c]);
const iterator = d.values();
for (let i = 0; i < 9; i++) {
    console.log(iterator.next());
}

I obviously get them in order, instead of having them shuffled. Is there another (more idiomatic and/or effifcient) way than using a shuffling array function as from this question like this:

let setArray = Array.from(d);
shuffleArray(setArray);
const randomSet = new Set(setArray);

Upvotes: 3

Views: 1728

Answers (3)

Montaz Meah II
Montaz Meah II

Reputation: 53

Here's an answer that might not be fancy, but works. In Pseudo-code:

  1. Combine your arrays (which is looks like you're doing) either using spread or concat
  2. Create a new array which will hold your randomized shuffle. For now, it's empty.
  3. While your new array isn't the length of your merged array, pick a random number from the merged array. If that number isn't included in your new array, add it to your new array.

Upvotes: 0

Chris Cousins
Chris Cousins

Reputation: 1912

Randomize the arrays before you make the set, that way you get the set's benefit of removing duplicates but the ability for its data to be shuffled. This assumes a lot of things though (do you want to re-shuffle often?, will you be adding more items to the set later? ...)

const arr1 = [1, 2, 3];
const arr2 = [10, 20, 30];
const arr3 = [100, 200, 300];
const arrs = shuffle([ ...arr1, ...arr2, ...arr3 ]);

const d = new Set(arrs);
const iterator = d.values();
for (let i = 0; i < 9; i++) {
    console.log(iterator.next());
}

Upvotes: 2

user6878069
user6878069

Reputation:

if you asking is there a better function then maybe How can I shuffle an array? (ES2015 (ES6)) this will help.

if i dont understand your question then sorry.

Upvotes: 0

Related Questions