Goal: I am trying to build teams of 5 people. Each person has an integer elo (rank). My goal is to make all the teams as equal/fair as possible, by having the average elo of each team be as close as possible to one another.Approach: My initial thought was to go through the list of elos and take the highest elo player and pair it with the lowest elo player. I did this twice (4 people on each team), sorting the array of teams after each loop by the teams median elo. On the final loop, I took the last set of elos (5th teammate) and put the highest players with the lowest team averages. After my 3rd loop I noticed the biggest jump in the elo difference between the lowest team and highest team. Question: I am wondering if my 3rd loop's logic is the main problem, or if this whole approach in general is bad. I have tried searching for algorithms about this like the partition problem, but am having little success implementing it into my functions.Demo: https://jsfiddle.net/aanders50/8m7m9tdw/3/Omitted visual code that is in the JSFiddle abovevar elos = ['big array of integers'];var teams = [];     //store teamsvar teamCount = 0;  //number of total teamsvar teamSize = 5;   //number of players on each teamfunction myFunction() { teamCount = elos.length / teamSize; teams.length = 0; var i = 0; //order default list of elos elos.sort(); //add 1 high and 1 low elo to each team for (i = 0; i < teamCount; i++) {   teams[i] = new Array();   teams[i][0] = elos.splice(0,1);   teams[i][1] = elos.splice(elos.length-1,1); } //first sort by median elo sortTeams(); $(#dif1).html(getMedian(teams[teams.length - 1]) - getMedian(teams[0])); //add another high and another low elo to each team for (i = teamCount-1; i > -1; i--) {   teams[i][2] = elos.splice(0,1);   teams[i][3] = elos.splice(elos.length-1,1); } //second sort by median elo sortTeams(); $(#dif2).html(getMedian(teams[teams.length - 1]) - getMedian(teams[0])); //add highest remaining elo to lowest median elo team for (i = 0; i < teamCount; i++) {   teams[i][4] = elos.splice(elos.length-1,1); } //3rd and final sort by median elo sortTeams(); $(#dif3).html(getMedian(teams[teams.length - 1]) - getMedian(teams[0])); //display results printTeams();}//sort each team by average elofunction sortTeams() { teams.sort(function (a, b) {  a = getMedian(a);  b = getMedian(b);  if (a > b) {    return 1;  }  if (a < b) {    return -1;  }  return 0;  });}//get average elo of each teamfunction getMedian(numberArray) {   var sum = numberArray.reduce(function(a,b) {     return Number(a) + Number(b);   });   return (sum / teamSize);}
Guidance on grouping equal sets of numbers, so each group has a similar average
javascript;sorting