Generate all possible heads-ups from an array
I am trying to find an efficient way to create matches for players in an array and return all possible matches for all players in a multidimensional array without duplicating matches.
Here's my example:
// input
var players = [
{player: 'sam' }, {player: 'bob' }, {player: 'tim' }, {player: 'kevin' }
];
// output
var mathups = [
[{player: 'sam'}, {player: 'bob}],
[{player: 'sam'}, {player: 'tim'}],
[{player: 'sam'}, {player: 'kevin'}],
[{player: 'bob'}, {player: 'tim'}],
[{player: 'bob'}, {player: 'kevin'}]
... and so on
];
Does anyone have any suggestions on how to do this with vanilla JS or using something like lodash or underscore?
+3
source to share
2 answers
Combinations can be generated like this without an external library:
var players = [
{player: 'sam' }, {player: 'bob' }, {player: 'tim' }, {player: 'kevin' }
];
var m = [];
for (var i = 0; i < players.length; i++) {
for (var j = i+1; j < players.length; j++) {
m.push([players[i], players[j]]);
}
}
console.log(JSON.stringify(m,null, 2));
+3
source to share
This should do the trick if there are duplicates in it.
var players = [{
player: 'sam'
}, {
player: 'bob'
}, {
player: 'tim'
}, {
player: 'kevin'
}];
function makeMatch()
{
var matchList = [];
for (var i=0; i<players.length; i++)
{
for (var j=i+1; j<players.length; j++)
{
matchList.push([{player: players[i].player}, {player: players[j].player}]);
}
}
console.log(matchList);
}
makeMatch();
+1
source to share