Get or Remove Random Array Elements Tutorial

Published :
Author :
Adam Khoury
Since JavaScript does not have built in methods for selecting or removing array elements randomly, we will demonstrate how to extend the Array object to supply it with those types of methods. The first example shows how to get a random array element without affecting the original array, the second example shows how to randomly splice an element from an array which removes the target item from the array. We also show how to extend the JavaScript Array object with these custom methods. Get a random value inside an array (does not alter the original array) var my_array = ['A','B','C','D','E','F','G']; var ri = Math.floor(Math.random() * my_array.length); // Random Index position in the array var result = my_array[ri]; Splice a random element out of an array (alters the original array) var my_array = ['A','B','C','D','E','F','G']; var ri = Math.floor(Math.random() * my_array.length); // Random Index position in the array var rs = my_array.splice(ri, 1); // Splice out a random element using the ri var Extend the JavaScript Array object using both examples above Array.prototype.randsplice = function(){ var ri = Math.floor(Math.random() * this.length); var rs = this.splice(ri, 1); return rs; } Array.prototype.randval = function(){ var ri = Math.floor(Math.random() * this.length); var val = this[ri]; return val; } var my_array = ['A','B','C','D','E','F','G']; var result = my_array.randsplice(); document.write(result); document.write("<hr>"); document.write(my_array);