Q:

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. 

A:

We start with inventing an array method to properly shuffle the arrays. Afterwards our job is simple. I guess the following should do it.

Array.prototype.shuffle = function(){
  var i = this.length,
      j,
    tmp;
  while (i > 1) {
    j = Math.floor(Math.random()*i--);
    tmp = this[i];
    this[i] = this[j];
    this[j] = tmp;
  }
  return this;
};

function groupPlayers(a,n){
  var result = [],
    remnants = a.shuffle().splice(-(a.length % n) || a.length); // the ones out in the cold
  for (var i = 0, len = a.length; i < len; i += len/n ) result.push(a.slice(i,i + len/n));
  return remnants.reduce((res,e,i,a) => (res[res.length-1-i].push(e),res),result); // finding a home for remnants
}


var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14],
 result = groupPlayers(arr,3);
console.log(result);

