Picking 2 random elements from array

前端 未结 9 892
一向
一向 2020-12-16 18:32

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:



        
相关标签:
9条回答
  • 2020-12-16 19:31

    It can be done using built-in functionality (slice and sort),

    var n = 2
        randomItems = array.sort(() => .5 - Math.random()).slice(0, n);
    
    0 讨论(0)
  • 2020-12-16 19:34

    If you want to get n random elements you could create a shuffled version of your list and then return the first n elements of the shuffled array as a result.

    0 讨论(0)
  • 2020-12-16 19:34

    You can do something easy like this

    const elements = ['indie hackers', 'twitter', 'product hunt', 'linkedIn'];
    const randomIndex = Math.floor(Math.random() * elements.length);
    const a = elements[randomIndex];
    
    const filteredElements = [...elements].splice(randomIndex, 1);
    const b = filteredElements[Math.floor(Math.random() * elements.length)];
    

    a and b will be your random elements.

    0 讨论(0)
提交回复
热议问题