50 random unique elements from an array of 1000 el

2020-02-14 02:53发布

What is the simplest way to get 50 random unique elements from an array of 1000 elements ?

text = new Array();
for(i=0;i<1000;i++){ text[i]=i; }   //array populated
// now I need to get 50 random unique elements from this array.

7条回答
做自己的国王
2楼-- · 2020-02-14 03:40

In case you meant unique values:

Demo

var old_arr = [0,1,2,3,4,5,6,7,8,9], new_array = [];

for (var i = 0; i < 5; i++) {
    var rand_elem = old_arr[Math.floor(Math.random() * old_arr.length)];

    if (arrIndex(old_arr[rand_elem], new_array) == -1) {
        new_array.push(rand_elem);
    } else {
        i--;
    }
}

function arrIndex(to_find, arr) {//own function for IE support
    if (Array.prototype.indexOf) {
        return arr.indexOf(to_find);
    }
    for (var i = 0, len = arr.length; i < len; i++) {
        if (i in arr && arr[i] === to_find) {
            return i;
        }
    }
    return -1;
}

In case you meant unique indexs:

  • Generate random indexes and store the indexes in an array and make checks to prevent duplicates
  • Start removing the elements of the array after you get them, (you might have problems if you cache the length, so don't)
查看更多
登录 后发表回答