Random select array item without duplicates without removing items (JavaScript)

后端 未结 3 677
不思量自难忘°
不思量自难忘° 2021-01-16 02:52

I have seen many questions concerning randomly selecting array items without repeating. However, most of them are answered by using the splice method. But this removes items

3条回答
  •  有刺的猬
    2021-01-16 03:32

    If you want to go through an array in random order without modifying the original array:

    1. Make a copy of the array with ary.slice() (this will copy the array, but not its values if they are objects).
    2. Shuffle the copy.
    3. Iterate through the copy.

    var items = ["a", "b", "c", "d", "e", "f", "g"];
    
    var copy = getShuffledCopy(items);
    copy.forEach(function (el) {
        console.log(el);
    });
    
    
    
    function getShuffledCopy(ary){
        var copy = ary.slice();
        shuffle(copy);
        return copy;
    }
    
    function swap(ary, pos1, pos2) {
        var tmp = ary[pos1];
        ary[pos1] = ary[pos2];
        ary[pos2] = tmp;
    }
    
    function shuffle(ary){ 
        // Fisher-Yates shuffle
        for(var i = ary.length - 1; i >= 1; i -= 1) {
            swap(ary, Math.floor(Math.random() * i), i);
        }
    }

提交回复
热议问题