简体   繁体   中英

How to select Random Element From an Array and Remove it from the List

Can you please let me know how I can select a number randomly from a list and also remove it from the array for the next time? For example I have an array as:

var items   = new Array( 2,3,4,5,6,7,8,9,10 );

now I would like to pick one item when a Pick button pushed and add the picked value to a div and also remove the picked item from the array so in next Pick button push it wont be there until to select all of items.

Thanks for your time

Array.splice()

 var items = ["a","b","c","d"]; var randomIndex = Math.floor(Math.random() * items.length); var randomItem = items.splice(randomIndex, 1)[0]; console.log("random item: %o", randomItem); console.log("remaining items: %o", items);

If shuffling the array doesn't matter :

items.sort(function() { return 0.5 - Math.random();}).pop();

FIDDLE

EDIT:

I should probably have been a little clearer as the fiddle doesn't really take advantage of the shuffling.
The array only needs to be shuffled once to make it random, after that there is no reason to shuffle it again, just pop of the last value:

var items   = new Array( 2,3,4,5,6,7,8,9,10 );

items.sort(function() { return 0.5 - Math.random();})

$('#test').on('click', function() {
    var ran = items.pop();
    alert(ran ? ran : 'No more numbers in array');
});

JSPERF
JSFIDDLE

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