【问题标题】:Creating array of fixed length and unique objects in javascript and MongoDB [duplicate]在javascript和MongoDB中创建固定长度和唯一对象的数组[重复]
【发布时间】:2022-01-12 12:53:37
【问题描述】:

我正在尝试创建一个包含 12 种独特产品的数组。这些产品是从从我的 MONGODB 数据库中检索到的产品列表中选择的。我可以很好地创建数组,但我似乎无法每次都将数组的长度设为 12。我需要数组的最小长度为 12,数组的最大长度也为 12。

这是我下面的代码,每次运行此代码时,randomProducts.length 通常是随机长度,而不是 12。


Products.find({}).limit(12).exec(function (err, randProducts) {
    var randomProducts = []
    for (let i = 0; i < randProducts.length; i++) {
      var rand = Math.floor(Math.random() * (randProducts.length - 0) + 0);
      if (randomProducts.includes(randProducts[rand]) == false) {
        randomProducts.push(randProducts[rand])
      }
    }
    console.log(randomProducts.length)
})

【问题讨论】:

  • 商店是否包含重复项?或者您只是想获得 12 种产品(您已经知道它们没有重复)然后洗牌? (我猜这些对象无论如何都会不同,但是...)
  • 商店不包含重复项。所有的物品都是独一无二的。但是,由于我正在生成从 0 到 randProducts.length 的随机产品集,因此产品可能会在 randomProducts 数组中重复。我不希望产品在数组中出现两次。
  • 既然如此,你就是shuffling an array

标签: javascript node.js arrays mongodb


【解决方案1】:

由于您的 MongoDB 查询调用了 .limit(12),您开始使用 12 种产品的初始集合。

从一组 12 个元素中选择 12 个随机元素也称为 shufflerandomizing 数组。多次解释洗牌数组:How to randomize (shuffle) a JavaScript array?

要从更大的数组中选择 12 个随机元素,请看这里: How to get a number of random elements from an array?

您的代码存在您尝试 12 次随机选择产品的问题。但是,如果产品已经被挑选出来(在很多情况下都是这样),你什么也不做。所以你必须非常幸运才能以随机顺序获得所有 12 种产品。

【讨论】:

猜你喜欢
  • 2011-12-27
  • 2020-01-26
  • 1970-01-01
  • 1970-01-01
  • 2017-01-11
  • 1970-01-01
  • 2011-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多