用javascript平等排名

时间:2014-02-19 08:46:16

标签: javascript arrays

我有一个数组“播放器”,其中包含分数为

的玩家对象
player['toto'].point = 15;
player['titi'].point = 8;
player['tete'].point = 5;
player['tata'].point = 10;
player['tutu'].point = 15;

我想知道前3名最佳球员,可能有关系。 在我们的示例中,这是我期望的结果:

best[1].player = "TOTO, TUTU";
best[1].point = 15;
best[2].player="TATA";
best[2].point = 10;
best[3].player="TITI";
best[2].point = 8;

请注意,我尝试显示任何关系。在该示例中,有两个玩家是第一位置:TOTO和TUTU。 我认为我真的没有javascript的水平。有人帮我吗?感谢。

3 个答案:

答案 0 :(得分:1)

这样做:

player = {
    'toto': { point: 15},
    'titi': { point: 8},
    'tete': { point: 5},
    'tata': { point: 10},
    'tutu': { point: 15 }
}

var playerArr = [];
for(var key in player) { 
   player[key].name = key;
   playerArr.push(player[key]);
}

playerArr.sort(function(a, b){
    if (a.point == b.point) return 0;
    if (a.point > b.point) return -1;
    return 1;
})

var best = [];
for(var i = 0; i < playerArr.length; i++) {
    var point = playerArr[i].point;
    if (best.length == 0 || best[best.length - 1].point != point)
        best.push({ point: point, text: playerArr[i].name });        
    else 
        best[best.length - 1].text += ", " + playerArr[i].name;
}

// output
for(var i = 0; i < 3; i++) {
    console.log("best[" + (i + 1) + "].player = " + best[i].text + ";")
    console.log("best[" + (i + 1) + "].point = " + best[i].point + ";")    
}

答案 1 :(得分:1)

解决方案可以更简单一些:

var player = {
    'toto': { point: 15},
    'titi': { point: 8},
    'tete': { point: 5},
    'tata': { point: 10},
    'tutu': { point: 15 }
},
best = [];

for (var el in player) {
    best.push({player: el, point: player[el].point})
}

best.sort(function(a, b) {
    return b.point - a.point;
})
.forEach(function(el, i, arr) {
    if (arr[i+1] && el.point == arr[i+1].point) {
        el.player += ', ' + arr.splice(i+1, 1)[0].player;
    }
});

现在best包含

[
    {"player":"toto, tutu","point":15},
    {"player":"tata","point":10},
    {"player":"titi","point":8},
    {"player":"tete","point":5}
]

答案 2 :(得分:0)

解决方案包括几个步骤。

var player = {
  toto: { point: 15 },
  titi: { point: 8 },
  tete: { point: 5 },
  tata: { point: 10 },
  tutu: { point: 15 }
};

第一步是从player对象的属性中创建一个数组,然后根据相反的顺序对数组进行排序:

var scores = Object.keys(player).map(function(key) {
  return {
    name: key,
    points: player[key].point
  };
}).sort(function(a, b) {
  if (a.points != b.points) {
    return b.points - a.points;
  }
  return 0;
});

然后,迭代并格式化它:

var i = 0,
j = 1,
current;

function getName(item)
{
  return item.name;
}

// only print top 3 (variable j)
while (i < scores.length && j <= 3) {
  current = i++;

  // grab more names based on similar score    
  while (i < scores.length && scores[i].points == scores[current].points) {
    ++i;
  }

  console.log(
    '%d - %d - %s', 
    j, 
    scores[current].points, 
    scores.slice(current, i).map(getName).join(' ')
  );

  ++j;
}