简体   繁体   English

使用 Javascript 随机分组数组元素

[英]Randomly group elements of array using Javascript

I have JSON file, from which I display the data:我有 JSON 文件,我从中显示数据:

data: [
    {
    name: "john"
    },
    {
    name: "lora"
    },
    ...
    ]

In total I have 16 names.我总共有 16 个名字。 What I want to do is to randomly group this array by 4 people, total 4 groups.我想要做的是将这个数组随机分组为 4 人,共 4 组。 What is the best way to do this using react.js?使用 react.js 执行此操作的最佳方法是什么?

I don't think a solution to this is React-specific, just vanilla javascript will do.我不认为这个解决方案是特定于 React 的,只需 vanilla javascript 就可以了。 First, randomize your entire array ( How to randomize (shuffle) a JavaScript array? has a couple different answers you could use).首先,随机化整个数组( How to randomize (shuffle) a JavaScript array?有几个不同的答案可以使用)。 Then, it should be pretty straightforward to iterate over the array and break each group of 4 successive names out.然后,迭代数组并将每组 4 个连续名称分开应该非常简单。

Here's a simple example with everything built into one function (comments included to explain what's going on):这是一个简单的例子,所有东西都内置在一个 function 中(包括注释以解释发生了什么):

const data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

function randomizeAndSplit(data, chunkSize) {
  var arrayOfArrays = [];
  var shuffled = [...data]; //make a copy so that we don't mutate the original array
  
  //shuffle the elements
  for (let i = shuffled.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }
  
  //split the shuffled version by the chunk size
  for (var i=0; i<shuffled.length; i+=chunkSize) {
     arrayOfArrays.push(shuffled.slice(i,i+chunkSize));
  }
  return arrayOfArrays;
}

console.log(randomizeAndSplit(data, 4))
//Example output: [[13, 7, 2, 14], [9, 12, 8, 15], [1, 16, 10, 3], [11, 6, 5, 4]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM