Niko Gamulin
Niko Gamulin

Reputation: 66565

Getting unique random items from array

Looking for a solution to this problem I have tried to follow several procedures suggested so far on SO but neither worked.

I want to select a random number of random unique items from selected array. In order to do that, I've written the following function, which always returns duplicates instead of unique items:

function getRandomItemsCombination(min, max, sourceArray){
    var items = {};
    //var itemsCount = Math.floor(Math.random() * (max - min + 1)) + min;
    var itemsCount = random.integer(min, max);
    //var randomItem = getRandomArrayElement(sourceArray);
    var randomItem;
    var arrIntegers = []
    while(arrIntegers.length < itemsCount){
        var randomnumber=Math.ceil(Math.random()*(sourceArray.length - 1))
        var found=false;
        for(var i=0;i<arrIntegers.length;i++){
            if(arrIntegers[i]==randomnumber){found=true;break}
        }
        if(!found)arrIntegers[arrIntegers.length]=randomnumber;
    }

    items.items = [];
    var randomItemsIndex = {};
    items.quantities = [];
    var existing = false;

    for(var i = 0; i < itemsCount; i++){
        randomItem = sourceArray[arrIntegers[i]];
        var index = randomItemsIndex[randomItem.Long_desc];
        if(index == undefined){
            index = items.items.length;
            randomItemsIndex[randomItem.Long_desc] = index;
            existing = false;
        }
        else {
            existing = true;
        }
        items.items[index] = randomItem;
        existing = false;
    }
    return items;
}

Does anyone know why it doesn't return unique items?

Thanks!

Upvotes: 0

Views: 89

Answers (1)

Mohamad Shiralizadeh
Mohamad Shiralizadeh

Reputation: 8765

You can use underscorejs sample function

_.sample(list, [n])

Produce a random sample from the list. Pass a number to return n random elements from the list. Otherwise a single random item will be returned.

_.sample([1, 2, 3, 4, 5, 6]);
=> 4

_.sample([1, 2, 3, 4, 5, 6], 3);
=> [1, 6, 2]

http://underscorejs.org/#sample

Upvotes: 2

Related Questions