search

Home  >  Q&A  >  body text

javascript - One array taking random elements from another array

There is an array a=[4,19,23,44,56,1], create a new array b, and b randomly selects one element at a time from a until it is exhausted. Implemented in JavaScript

PHP中文网PHP中文网2809 days ago766

reply all(7)I'll reply

  • 高洛峰

    高洛峰2017-05-19 10:33:39

    You can shuffle a with pseudo-randomness, exchange the numbers in any two positions, do this n times to achieve the shuffling effect, and then assign it to b.

    Or just follow the steps. If code efficiency is not considered, the array operations provided by the lodash library can make the code more elegant:

    var src = [4,19,23,44,56,1];
    
    var shuffle = [];
    while(src.length > 0){
        var random_index = Math.floor(Math.random() * src.length);
        shuffle.push(src[random_index]);
        
        src = src.filter(function(el, i){
            return i != random_index;
        });
    }

    I thought of a better pseudorandom method, which is directly sorted randomly, the code is simpler, and the operation efficiency is high:

    var src = [4,19,23,44,56,1];
    
    var shuffle = src;
    shuffle.sort(function(){
        return Math.floor(Math.random() * 3) - 1;
    });

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-19 10:33:39

    var a=[4,19,23,44,56,1];
    var b=[];
    var c=[0,0,0,0,0,0];
    var aLen = a.length;
    while (c.indexOf(0)!=-1){
        var randomNum = Math.floor(Math.random()*aLen);
        if (c[randomNum] == 0){
            b.push(a[randomNum]);
            c[randomNum]=1
        }
    }
    console.log(b);

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-19 10:33:39

    The implementation is as follows:

    var a = [4,19,23,44,56,1];
    function randomSort(array){
        var newArray = [];
        for(let i = 0; i < array.length;){
            let j = Math.random() * array.length; // 获取随机的下标值
            j = ~~j; // 取整
            let item = array.splice(j, 1)[0]; // 从原数组中剔除选中的元素
            newArray.push(item);
      }
      return newArray;
    }
    randomSort(a);

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-19 10:33:39

    My idea is to traverse this array, get random elements in this array, delete them from array a and push them into array b, and so on

    var a = [4,19,23,44,56,1],
        aLen = a.length,
        b = [];
        
    // 定义删除数组中指定元素的方法
    Array.prototype.removeByValue = function(val) {
      for(var i=0; i<this.length; i++) {
        if(this[i] == val) {
          this.splice(i, 1);
          break;
        }
      }
    }
    
    // 遍历a数组
    for(var i=0; i<aLen; i++){
        var cur = a[Math.floor(Math.random()*a.length)]; //获取随机的元素
        a.removeByValue(cur);    // 从a中删除
        b.push(cur);            // 添加进b
    }
    
    console.log(b)

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-19 10:33:39

       var a=[4,19,23,44,56,1];
        function randomSelect(str){
            var leng= a.length;
            var b=[];
          while(leng!=0){
              b.push(a.splice(Math.random()*leng,1).join())
              leng--;
          }
           return b;
        }
        console.log(randomSelect(a));

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-19 10:33:39

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
        <script>
          //有一个数组a=[4,19,23,44,56,1],新建一个数组b,b从a中一次随机选取一个元素,取完为止。用JavaScript实现
          var a = [4,19,23,44,56,1];
          var b = [];
    
          function findInArr(num, arr){
            for(var i=0; i<arr.length; i++){
              if(num == arr[i]){
                return true;
              }
            }
            return false;
          }
    
          function rnd(m,n){
            return m + Math.floor(Math.random()*(n-m));
          }
    
          function randomPass(arr){
            var len = arr.length;
            var rndIndex = rnd(0,len-1);
            console.log(rndIndex);
            var temp = arr[rndIndex];
            if(!findInArr(temp,b)){
              b.push(temp);
              arr.splice(rndIndex,1);
              if(arr.length > 0){
                randomPass(arr);
              }
            }
          }
    
          randomPass(a);
          console.log(b); // [44, 56, 19, 23, 4, 1] (每次随机)
          console.log(a); // []
    
        </script>
      </body>
    </html>
    

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-19 10:33:39

    I won’t write it down to the fourth floor. I just randomly select one from the array one at a time. After randomization, remove it from the array. Continue randomizing. Just push the removed ones into the new array and it will be ok

    reply
    0
  • Cancelreply