0

I have JSON file, from which I display the data:

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

In total I have 16 names. What I want to do is to randomly group this array by 4 people, total 4 groups. What is the best way to do this using react.js?

2 Answers2

0

I don't think a solution to this is React-specific, just vanilla javascript will do. First, randomize your entire array (How to randomize (shuffle) a JavaScript array? has a couple different answers you could use). Then, it should be pretty straightforward to iterate over the array and break each group of 4 successive names out.

Jim J
  • 546
  • 3
  • 11
0

Here's a simple example with everything built into one function (comments included to explain what's going on):

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]]

jnpdx
  • 45,847
  • 6
  • 64
  • 94