我想知道除了手动排序以下内容(示例)之外是否还有其他方法:
BBB+
BB
AA+
A-
BB-
A
B
AAA
我们正在尝试将之前的字符串排序如下:
AAA
AA+
A
A-
BBB+
BB
BB-
B
有没有比较加号和减号先加号的自动排序?
最佳答案
正如我在评论中所述,我们可以将评分更改为数字,这样我们就可以使用基本排序而不是复杂的字母排序。
const ratings = [
"BBB+",
"BB",
"AA+",
"A-",
"BB-",
"A",
"B",
"AAA"
];
// Each letter should be enough apart.
// Technically we can go for smaller numbers.
// But that can break if not carefull once we start using Moodys or S&P instead of Fitch.
// Since AA- is lower than AA, the - character has to be a negative number.
const weights = {
"A": 10000,
"B": 1000,
"C": 100,
"D": 10,
"+": 1,
"-": -1
};
const rating_values = ratings
.map( rating => ( {
rating,
"value": rating
.split( '' )
.map( character => weights[ character ] )
.reduce( ( a, b ) => a + b )
} ) );
const sorted_ratings = rating_values
.sort( ( a, b ) => b.value - a.value )
.map( obj => obj.rating );
console.log( sorted_ratings );
关于javascript - 对具有加号或减号的字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51212499/