0

我在数组中有这个结构:

[
    {
        "playerName": "Stack",
        "leaguePoints": 100,
        "wins": 280,
        "miniSeries": {
            "progress": "WNN",
            "losses": 0,
            "wins": 1
        }
    },
    {
        "playerName": "Overflow",
        "leaguePoints": 90,
        "wins": 280
    }
    {
        "playerName": "StackOverflow",
        "leaguePoints": 0,
        "wins": 100
    }
]

我需要像这样对数组元素进行排序:

如果leaguePoints = 100,则按(miniSeries.wins+miniSeries.losses(玩的游戏更多,排名更高))或 miniSeries.progress 中剩余的 N(中立)数量(更少 Ns,排名更高)排序

如果leaguePoints < 100 然后按leaguePoints 排序

如果 LeaguePoints = 0 则按胜利排序

我一直在使用Ege Özcan 的多参数排序,它确实按联赛积分和胜利排序,但我无法让它与 miniSeries 一起使用。

它应该如何最终看起来像:

Name    leaguePoints    Wins    MiniSeries
Stack   100             10      LWN
Stack   100             25      WNN
Stack   100             5       NNN
Stack   99              50      ---
Stack   70              250     ---
Stack   0               300     ---
Stack   0               200     ---
Stack   0               100     ---
4

2 回答 2

0

I think you want

function byProgress(a, b) {
    // less "N"s in the value
    return b.split("N").length - a.split("N").length;
}
function byMiniSeries(a, b) {
    // more games played
    return a.wins+a.losses - b.wins-b.losses || byProgress(a.progress, b.progress);
}
function byRank(a, b) {
    // highest league
    return a.leaguePoints - b.leaguePoints || (a.leaguePoints == 0
      ? a.wins - b.wins
      : (a.leaguePoints == 100 
        ? byMiniSeries(a.miniSeries, b.miniSeries)
        : 0 ) );
}
playerArray.sort(byRank);

The || uses short-circuit evaluation, the right operand will be returned if the left one is falsy (here: 0, i.e. the values are equal).

于 2013-10-14T18:29:59.270 回答
0

我认为您最好进行 2 次处理。
首先将数据分为 3 组,leaguePoints100leaguePoints0,其余的。

您知道如何分别对每个组进行排序,然后使用Array.concat()合并三个排序后的数组,请参见此处的示例。

Lo-Dash可以使任务变得简单,首先:groupBy() leaguePoints

groups = _.groupBy(data, function(item) {
  switch (item.leaguePoints) {
    case 100:
        return 'leaguePoints100';
    case 0:
        return 'leaguePoints0';
    default:
        return 'other';
  }
);

然后sortBy()是三组:

groups['leaguePoints100'] = _.sortBy(group['leaguePoints100'], sortLeaguePoints100);
groups['leaguePoints0'] = _.sortBy(group['leaguePoints0'], 'wins');
groups['other'] = _.sortBy(group['other'], 'leaguePoints');

这使代码更清晰,但确实是机械的。
亲亲,伙计。

于 2013-10-14T18:26:15.727 回答