I have a task of organizing an array of objects that represent game players by assigning each player to a group number based on their current group value.
The challenge is to ensure that each group has as close to four players as possible, while also accommodating players who specifically want to be in certain groups that cannot be broken up (but can be renamed or merged).
Some players have unassigned or null groups (indicating they have no preference) and others have custom group values indicating they want to play with specific people.
var players = [
{name: "A", group: null},
{name: "B", group: null},
{name: "C", group: null},
{name: "D", group: null},
{name: "E", group: null},
{name: "cA", group: "custom1"},
{name: "cB", group: "custom1"},
{name: "cC", group: "custom2"},
{name: "cD", group: "custom2"},
{name: "cE", group: "custom3"},
{name: "cF", group: "custom3"}];
I am looking for a solution to organize this array so that it results in something similar to the following:
var resolvedGroup = [
{name: "A", group: 1},
{name: "B", group: 1},
{name: "C", group: 1},
{name: "D", group: 1},
{name: "cA", group: "customMerged1"},
{name: "cB", group: "customMerged1"},
{name: "cC", group: "customMerged1"},
{name: "cD", group: "customMerged1"},
{name: "cE", group: 2},
{name: "cF", group: 2},
{name: "E", group: 2}
]
In this updated arrangement, the first four players are assigned to group 1, while those with custom groups are merged into larger groups of four if possible. If not possible, they will join other players from the "null" group to form groups as close to four as possible. The actual names of the groups are not important; what matters is ensuring that each player stays with their initial group members even after being merged with another custom group.