What is the most efficient way to select 2 unique random elements from an array (ie, make sure the same element is not selected twice).
I have so far:
While shuffle the array and pick the first two is correct.
You don't need to shuffle the whole array.
Just shuffle the first two!
var arrElm = [1, 2, 3, 4, 5, 6, 7]
var toTake = 2
var maxToShuffle = Math.min(arrElm.length - 1, toTake)
for (let i = 0; i < maxToShuffle; i++) {
const toSwap = i + Math.floor(Math.random() * (arrElm.length - i))
;[arrElm[i], arrElm[toSwap]] = [arrElm[toSwap], arrElm[i]]
}
console.log(arrElm.slice(0, toTake))
basically the same as https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
Except you just quit early when you have enough item shuffled.