【问题标题】:Get random X items from array in javascript从javascript中的数组中获取随机X项
【发布时间】:2017-02-01 22:51:36
【问题描述】:

我有以下使用测试数据的小提琴,我正在使用 $.each 查看数据

我可以循环遍历没有问题,但是我想循环遍历数据,然后从中随机获取3个对象。

任何提示或技巧都会有所帮助:

https://jsfiddle.net/inkedraskal/pah44qv6/

$.each(testData,function(x, blah){
    //console.log(blah._id);

  //this gets each objects id & picture, but I want to get 3 random objects, and their corresponding data
  var activeValue = blah._id,
        pictureValue = blah.picture;


  var markUp = '';

  markUp += activeValue + pictureValue;

  console.log(markUp);
});

对于下面的问题,它们必须是唯一的**

【问题讨论】:

  • 三个随机项必须是唯一的吗?
  • 哦,好问题,是的,它们必须是独一无二的
  • 只寻找使用$.each 的解决方案?有什么具体原因吗?您可以查看我的答案,如果可以,请告诉我。

标签: javascript jquery json each


【解决方案1】:

我们可以创建getRandomEntry() 函数,该函数将使用Math.random() 函数返回数组元素之一。我们将创建一个循环,每次迭代时都会随机输入。

function getRandomEntry() {
  return testData[Math.round(Math.random() * (testData.length - 1))];
}

for (var i=0; i<3; i++) {
  var entry = getRandomEntry();
  console.log(entry._id, entry.picture);
}

如果您每次都需要一个唯一的条目。您可以将随机条目保存在单独的数组中,并检查新条目是否不完整。

var randomEntries = [];

function getRandomEntry() {
  return testData[Math.round(Math.random() * (testData.length - 1))];
}

function entryExists(entry) {
  return randomEntries.indexOf(entry) > -1;
}

for (var i=0; i<3; i++) {
  var entry;

  do {

    entry = getRandomEntry();

  } while(entryExists(entry))

  randomEntries.push(entry);
  console.log(entry._id, entry.picture);
}

【讨论】:

  • 这将无法满足他们需要是唯一的要求
  • 编辑了答案。
【解决方案2】:

您可以使用如下递归函数。

请注意,此实现可防止结果中出现重复

function getRandomObjects(array,selected,needed){
    /*
     *@param array array The array to pull from
     *@param selected array The array of results pulled so far
     *@param needed int The number of results we want
     */
    var length = array.length;
    var num = Math.floor(Math.random() * length) + 1; // get random number in bounds of array
    var exists=false; // make sure we didnt already pick this object
    $.each(selected,function(i,obj){
        if(obj.index==num)exists=true;
    })
    if(exists) getRandomObjects(array,selected,needed); // get a new one if this was a duplicate
    else selected.push(array[num]);
    if(selected.length!=needed) return getRandomObjects(array,selected,needed); // get another object if we need more
    else return selected; // return the final result set
}




var testData = [
  {
    "_id": "57e5d1a90c4206b128cd8654",
    "index": 0,
    "guid": "1f3269fc-0822-4c5a-9c52-8055155b407e",
    "isActive": true,
    "balance": "$3,026.95",
    "picture": "http://placehold.it/32x32"
  },
  {
    "_id": "57e5d1a9a986ccb2f41cf7b9",
    "index": 1,
    "guid": "a6b726b6-6466-4e48-8697-1c6bd7b1c79e",
    "isActive": true,
    "balance": "$2,642.74",
    "picture": "http://placehold.it/32x32"
  },
  {
    "_id": "57e5d1a9f98f8b2f6880de32",
    "index": 2,
    "guid": "e7d736cc-19e0-4bcb-8d0a-4d17442d8cee",
    "isActive": true,
    "balance": "$3,341.64",
    "picture": "http://placehold.it/32x32"
  },
  {
    "_id": "57e5d1a9e40ded5b017e45cd",
    "index": 3,
    "guid": "64230ca8-05c0-4c39-a931-794172475a32",
    "isActive": true,
    "balance": "$2,196.13",
    "picture": "http://placehold.it/32x32"
  },
  {
    "_id": "57e5d1a90cc30be769a06d7c",
    "index": 4,
    "guid": "d6618b78-753a-4ad0-bc14-3687d0b99196",
    "isActive": true,
    "balance": "$1,611.62",
    "picture": "http://placehold.it/32x32"
  },
  {
    "_id": "57e5d1a92481a43f50607415",
    "index": 5,
    "guid": "35ec8186-9494-4f89-ab89-bed7f39872c3",
    "isActive": true,
    "balance": "$3,148.87",
    "picture": "http://placehold.it/32x32"
  },
  {
    "_id": "57e5d1a9164f17c558ba7ce1",
    "index": 6,
    "guid": "244970a0-1ce2-405a-8d69-c7903f9bf5eb",
    "isActive": false,
    "balance": "$3,758.13",
    "picture": "http://placehold.it/32x32"
  },
  {
    "_id": "57e5d1a95afde31c5cf592a8",
    "index": 7,
    "guid": "aa30c82d-dd2b-420c-8b30-7d66cec8d10b",
    "isActive": true,
    "balance": "$1,311.40",
    "picture": "http://placehold.it/32x32"
  }
]


var randomObjects=getRandomObjects(testData,[],3);

console.log(randomObjects);
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

    【解决方案3】:

    下面的 sn-p 中的函数获取一个数组和一个数量 (X) 的项,并返回一个新数组,其中包含来自原始数组的 X 个唯一随机项:

    function getRandomItems(arr, items) {
      var ret = [];
      var indexes = [];
      var arr_length = arr.length;
      
      // If we don't have enough items to return - return the original array
      if (arr_length < items) {
        return arr;
      }
      
      while (ret.length < items) {
        i = Math.floor(Math.random() * arr_length);
        if (indexes.indexOf(i) == -1) {
          indexes[indexes.length] = i;
          ret[ret.length] = arr[i];
        }
      }
      return ret;
    }
    
    arr = ['a', 'b', 'c', 'd', 'e']
    console.log(getRandomItems(arr, 2))

    如果您想在代码中的每个 Array 上使用它作为“本机”函数,也可以将函数添加到 Array.prototype

    Array.prototype.getRandomItems = function(items) {
      var ret = [];
      var indexes = [];
      var arr_length = this.length;
      
      // If we don't have enough items to return - return the original array
      if (arr_length < items) {
        return this;
      }
      
      while (ret.length < items) {
        i = Math.floor(Math.random() * arr_length);
        if (indexes.indexOf(i) == -1) {
          indexes[indexes.length] = i;
          ret[ret.length] = this[i];
        }
      }
      return ret;
    }
    
    arr1 = ['a', 'b', 'c', 'd', 'e']
    arr2 = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
    
    console.log(arr1.getRandomItems(1))
    console.log(arr1.getRandomItems(2))
    console.log(arr2.getRandomItems(3))
    console.log(arr2.getRandomItems(4))

    【讨论】:

      【解决方案4】:

      你可以这样做

      var items = [1, 2, 3, 4, 5];
      var newItems = [];
      
      for(var i = 0; i < 3; i++) {
          var idx = Math.floor(Math.random() * items.length);
          newItems.push(items[idx]);
          items.splice(idx, 1);
      }
      
      console.log(newItems);
      

      【讨论】:

        猜你喜欢
        • 2011-08-20
        • 2020-05-13
        • 2018-06-19
        • 2022-10-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多