I've been doing searches like this for awhile, and I feel there is probably a better way of doing this. The situation is I have a double elimination tournament bracket and have to find one of the games. The winners and losers brackets are stored in an array, and then games are stored within each of those arrays.
我一直在做这样的搜索,我觉得可能有更好的方法。情况是我有一个双重消除锦标赛支架,必须找到其中一个游戏。获胜者和输家括号存储在一个数组中,然后游戏存储在每个数组中。
The structure looks like this
结构看起来像这样
{
tournament: {
brackets: [
{games: [{id:'x'},{id:'y'},...,{id:'z'}]},
{games: [{id:'x'},{id:'y'},...,{id:'z'}]}
]
]
}
}
This is the code I'm using to find an ID.
这是我用来查找ID的代码。
for (var i = 0; i < tournament.brackets.length; i++) {
for (var y = 0; y < tournament.brackets[i].games;length; y++) {
// Does the ID of this object match known ID
}
}
2 个解决方案
#1
1
Since you tagged the question ES6, there's indeed a better way to do this:
既然您标记了问题ES6,那么确实有更好的方法:
for (var bracket of tournament.brackets) {
for (var game of bracket.games) {
// Does the ID of this object match known ID
}
}
#2
1
A simple alternative (if you are searching often) would be to build a reverse lookup array based on the game id. Something like:
一个简单的替代方法(如果您经常搜索)将基于游戏ID构建反向查找数组。就像是:
var lookup = {};
for (var i = 0; i < tournament.brackets.length; i++) {
for (var y = 0; y < tournament.brackets[i].games.length; y++) {
lookup[tournament.brackets[i].games[y].id] = { bracket: i, game: y };
}
}
Then later:
function findGame( id, lookup, tournament ) {
if ( !lookup.hasOwnProperty( id ) )
return false;
var location = lookup[id];
return tournament.brackets[location.bracket].games[location.game];
}
#1
1
Since you tagged the question ES6, there's indeed a better way to do this:
既然您标记了问题ES6,那么确实有更好的方法:
for (var bracket of tournament.brackets) {
for (var game of bracket.games) {
// Does the ID of this object match known ID
}
}
#2
1
A simple alternative (if you are searching often) would be to build a reverse lookup array based on the game id. Something like:
一个简单的替代方法(如果您经常搜索)将基于游戏ID构建反向查找数组。就像是:
var lookup = {};
for (var i = 0; i < tournament.brackets.length; i++) {
for (var y = 0; y < tournament.brackets[i].games.length; y++) {
lookup[tournament.brackets[i].games[y].id] = { bracket: i, game: y };
}
}
Then later:
function findGame( id, lookup, tournament ) {
if ( !lookup.hasOwnProperty( id ) )
return false;
var location = lookup[id];
return tournament.brackets[location.bracket].games[location.game];
}