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

后端 未结 3 708
不思量自难忘°
不思量自难忘° 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条回答
  •  猫巷女王i
    2021-01-16 03:55

    I don't get very well what you're trying to achieve, but here's one way I'd get random items once

    var letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"];
    var getRandom = (function (array) {
        var notGivenItems = array.map(function (el) {return el;}),
        var getIndex = function () {
          return Math.floor(Math.random() * notGivenItems.length);
        };
    
        return function () {
            if (notGivenItems.length === 0) {
                return;
            }
    
            return notGivenItems.splice(getIndex(), 1)[0];
        };
    })(letters); // items, in your case
    
    getRandom(); // some letter
    getRandom(); // some other letter
    ...
    getRandom(); // different letters until all are given
    
    // if the method is called more times than the array length it'll return undefined
    

    EDIT: Improved performance due to @JLRishe comment

提交回复
热议问题