【发布时间】:2017-09-12 15:57:53
【问题描述】:
Javascript数组排序比较函数问题, 我创建了下面的数组需要将一列排序为降序并将一列保持为升序,使用简单的比较函数但结果不正确。 它极大地帮助我解决了这个问题,
var homes =[
{score: "1.40", tier: "Tier-1", regionKey: 12, regionName: "Northern America"},
{score: "1.40", tier: "Tier-1", regionKey: 21, regionName: "Northern Europe"},
{score: "1.40", tier: "Tier-1", regionKey: 0, regionName: "Rest of World (ISO)"},
{score: "1.90", tier: "Tier-2", regionKey: 0, regionName: "Rest of World (ISO)"},
{score: "2.40", tier: "Tier-2", regionKey: 12, regionName: "Northern America"},
{score: "2.20", tier: "Tier-2", regionKey: 22, regionName: "Southern Europe"},
{score: "2.30", tier: "Tier-2", regionKey: 20, regionName: "Eastern Europe"},
{score: "1.80", tier: "Tier-2", regionKey: 10, regionName: "Central America"},
{score: "2.20", tier: "Tier-2", regionKey: 20, regionName: "Eastern Europe"},
{score: "1.80", tier: "Tier-2", regionKey: 22, regionName: "Southern Europe"},
{score: "2.60", tier: "Tier-3", regionKey: 65, regionName: "Eastern Europe"},
];
homes.sort(scoreComparison);
function scoreComparison(a, b) {
var tierA = a.tier;
var tierB = b.tier;
var scoreA = a.score*100;
var scoreB = b.score*100;
var comparison = 0;
if (tierA === tierB) {
if (scoreA > scoreB) {
comparison = -1;
} else if (scoreA < scoreB) {
comparison = 1;
}
return comparison;
}
}
console.log(homes);
【问题讨论】:
-
让我们试试 home.sort((a, b) => { return a.tier.localeCompare(b.tier) || b.score - a.score; })
-
哪一列是降序/升序?
-
分数列降序,层列升序
-
感谢泰乐工作,请提供解释。
-
@aryan,它可能不适用于像
'Tier-10'这样的字符串。这是在'Tier-2'之前排序的
标签: javascript arrays sorting compare