GreenRails GreenRails - 20 days ago 4x
Javascript Question

Removing all items from an array (individually)

I have an array with a finite number of items in it. I want to randomly remove items until all the items have been used once.

Example [1,2,3,4,5]

Random number 5 is used, so I don't want that again.
Random number 2 is used, so I don't want that again.
And so on..

I could have another list of used numbers and check that the new random number is not in it, but that could take a long time when there is only 1 or two numbers left in the array out of 50.

Is there a way to remove an item from an array in javascript? Does it create a new array and would that be inefficient?

Are arrays the wrong way to do this?

EDIT: A few good answers here. I ended up randomizing the array list and then splicing the first item which is the one I took out.


Use the combination of Math.random() and splice():

var arr = [1, 2, 3, 4, 5],

while ( arr.length ) {
    i = Math.floor( Math.random() * arr.length );
    alert( arr.splice(i, 1) );    

Live demo:

Update: You can use this function to remove a random item from your array:

function popRandomItem(arr) {   
    return arr.length ? 
        arr.splice(Math.floor(Math.random() * arr.length), 1)[0] : null;

So, if you have an array x, then popRandomItem(x) will remove a random item from that array and return that item. (If x is an empty array, the function will return null.)

Live demo:,console