Jose Miguel Ledón Jose Miguel Ledón - 3 months ago 16
Javascript Question

divide an array of numbers into subarrays in equally parts and randomized from a given integer

to make it clearer I have an array of player ids and I want to divide into X number of groups equally and randomly, but when the number is odd the group 1 need to be the subarray with the small number of parts: like this example:


  • Player ids: [1,2,3,4,5,6,7,8,9,10,11,12,13,14]

  • Number of groups: 3

  • expected result: [14,12,2,1], [3,4,8,13,11], [5,6,7,9,10]



I cases when the number is even is easier but i don't know how to achieve this case. I need some help to know how to.

Answer

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
var i = arr.length;
var partLen = i / 3;
var parentArr = [],
  temp = [];

function shuffle(array) {
  var currentIndex = array.length,
    temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}
var shuffled = shuffle(arr);
while (i--) {
  if (temp.length >= partLen) {
    parentArr.unshift(temp);
    temp = [];
  }
  temp.push(shuffled[i]);
}
if (temp.length) {
  parentArr.unshift(temp);
  temp = [];
}
console.log(JSON.stringify(parentArr, null, 4));