Randomly group elements of array using Javascript

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 thoughts on “Randomly group elements of array using Javascript”

  1. 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]]
    
    
    Reply

Leave a Comment