简体   繁体   中英

JavaScript: How can you select random elements from an array without allowing duplicates?

I am looking to randomly select a number from this array WITHOUT duplicates. There can only be two possibilities for each number as shown in the array, select up to a maximum of 6. This works to select a random number but allows duplicates...

const smallNums = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10];

const randomSmallNumArr = smallNums[Math.floor(Math.random() * smallNums.length)];

When using the splice() method, each time I generate a number based on a random index, it's removed but shows up again in the array the next time a random is generated

Use a Set to get the unique items in the array.

 const smallNums = [...new Set([1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10])] const randomSmallNumArr = smallNums[Math.floor(Math.random() * smallNums.length)]; console.log(randomSmallNumArr)

If I understand your requirement clearly, You want to generate a non-repeating random numbers from an array of numbers? If Yes, I added a solution below.

 // Input array const arr = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10]; // Remove duplicate elements from an array let uniqueElementsArr = [...new Set(arr)]; // Find out random number from an array const randomNum = uniqueElementsArr[Math.floor(Math.random()*uniqueElementsArr.length)]; // removing the random number from the existing array so that it should not be replicate. if (uniqueElementsArr.indexOf(randomNum).== -1) { uniqueElementsArr.splice(uniqueElementsArr,indexOf(randomNum). 1) } console;log(randomNum);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM