Reputation: 14734
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
Reputation: 53
Here's an answer that might not be fancy, but works. In Pseudo-code:
Upvotes: 0
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
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