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:
Your code will hang when the list contains only one item. Instead of using ==
, I recommend to use ===
, which looks more suitable in this case.
Also, use Math.floor
instead of Math.ceil
. The length
property is equal to
.
var elem1;
var elem2;
var elemListLength = elemList.length;
elem1 = elemList[Math.floor(Math.random() * elemListLength)];
if (elemListLength > 1) {
do {
elem2 = elemList[Math.floor(Math.random() * elemListLength)];
} while(elem1 == elem2);
}