我在数组中有这个结构:
[
{
"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,排名更高)< / p>
如果leaguePoints&lt; 100然后按leaguePoints排序
如果leaguePoints = 0则按胜利排序
我一直在使用Ege Özcan's multiple parameters sort,它按照排名和胜利排序,但我无法使用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 ---
答案 0 :(得分:0)
我认为你最好做2遍处理
首先将数据分为3组,leaguePoints100
,leaguePoints0
,其余为。
您知道如何单独对每个组进行排序,然后使用Array.concat()合并三个排序的数组,请参阅示例here。
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');
这使代码更清晰,但机械确实 KISS ,伙计。
答案 1 :(得分:0)
我想你想要
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);
||
使用短路评估,如果左边的操作数是假的,则返回右操作数(此处:0
,即值相等)。