从数组

时间:2015-05-28 23:28:46

标签: javascript node.js underscore.js lodash

我正在尝试找到一种高效的方法来为阵列中的玩家创建对战,并为多维数组中的所有玩家返回所有可能的匹配,而不会重复任何匹配。

以下是我的例子:

// 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
];

有没有人对如何使用vanilla JS或使用lodash或者下划线等方面有任何建议?

2 个答案:

答案 0 :(得分:3)

组合可以像这样生成而无需外部库:

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));

答案 1 :(得分:1)

假设名称中有重复项,这应该可以解决问题。

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();