确保我的随机值数组不包含重复值

sty*_*ler 2 javascript random jquery

我想知道是否有人可以建议我如何确保我从另一个数组生成的随机数组不包含重复值,是否要确保arr2包含唯一值?

JS

var limit = 5,
    i = 0,
    arr1 = [12, 14, 67, 45, 8, 45, 56, 8, 33, 89],
    arr2 = [];

    for ( i; i < limit; i++ ){
        var rand = Math.floor((Math.random()*9)+1);
        arr2.push( arr1[rand] );
    }

    console.log(arr2);
Run Code Online (Sandbox Code Playgroud)

也许是一个将arr1 [rand]与arr2 [i]进行比较的if语句?

Pau*_*aul 6

创建一个临时数组,该数组是仅包含唯一值的arr1的副本:

// Copy unique values in arr1 into temp_arr
var temp_obj = {}, temp_arr = [], i;
for(i = arr1.length; i--;)
    temp_obj[arr1[i]] = 1;
for(i in temp_obj) 
    temp_arr.push(i);
Run Code Online (Sandbox Code Playgroud)

然后,您可以在temp_arr每次添加元素时删除该元素arr2.由于我们在复制时使用对象键我们有字符串,因此我们可以+在推入时将它们转换回数字arr2:

arr2.push(+temp_arr.splice(rand, 1)[0]);
Run Code Online (Sandbox Code Playgroud)

您还应该更改随机数的选择方式:

var rand = Math.floor(Math.random()*temp_arr.length);
Run Code Online (Sandbox Code Playgroud)

整码:

var limit = 5,
  arr1 = [12, 14, 67, 45, 8, 45, 56, 8, 33, 89],
  arr2 = [],
  rand, 
  temp_obj = {},
  temp_arr = []
  i;

// Copy unique values from arr1 into temp_arr
for(i = arr1.length; i--;)
    temp_obj[arr1[i]] = 1;
for(i in temp_obj)
    temp_arr.push(i);;

// Move elements one at a time from temp_arr to arr2 until limit is reached
for (var i = limit; i--;){
    rand = Math.floor(Math.random()*temp_arr.length);
    arr2.push(+temp_arr.splice(rand, 1)[0]);
}

console.log(arr2);
Run Code Online (Sandbox Code Playgroud)