JS randomly fetches N non repeating data from the specified array

  • 2020-03-30 03:19:17
  • OfStack


<script language="javascript">
//Returns num nonrepeating items from a given array arr at random
function getArrayItems(arr, num) {
    //Create a new array and copy the incoming array to perform operations instead of directly manipulating the incoming array.
    var temp_array = new Array();
    for (var index in arr) {
        temp_array.push(arr[index]);
    }
    //The retrieved numeric item is stored in this array
    var return_array = new Array();
    for (var i = 0; i<num; i++) {
        //Determines if the array still has elements to pull out, in case the index crosses the line
        if (temp_array.length>0) {
            //Generates a random index in the array
            var arrIndex = Math.floor(Math.random()*temp_array.length);
            //Copies the corresponding array element values of this random index
            return_array[i] = temp_array[arrIndex];
            //Then delete the array elements of this index, and temp_array becomes the new array
            temp_array.splice(arrIndex, 1);
        } else {
            //Exit the loop when all the items in the array have been retrieved, such as 20 items instead of 10 items in the array.
            break;
        }
    }
    return return_array;
}
// test 
var ArrList=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33];
alert(getArrayItems(ArrList,6));
</script>


Related articles: