按分数对字符串行数组进行排名

时间:2014-12-22 22:26:11

标签: javascript arrays sorting ranking

我需要从输入字符串行创建一个新的字符串行数组。输入数组只包含一个国家/地区名称,后跟其分数。我的目标是通过添加一个值来重新创建此数组,该值是该国家/地区的排名。请查看下面的骨架代码。

<!DOCTYPE html>
<html><head><meta charset="UTF-8"></head>
<body>
<button type="button" onclick="myRankFunction( ['AFG\t3,416', 'AUS\t1,414', 'BRA\t2,073', 'JPN\t1,316'] )">Rank</button>
<script>
/*
* The function must return a new rowlist in the format: 
*   Rank[TAB]Country[TAB]Score
*   - notice that the input rowlist DOESN'T contain the "Rank" part in the begining of the row;
*   - Rank is an integer number which represents the country's position in the ranking;
*   - Score is a float number; more Score means better Rank.
*/
function myRankFunction(rowlist)
{
    var newrowlist = [];
    var s1 = [], s2 = [];
    for(i = 0; i < rowlist.length; i++)
    {
        s1 = rowlist[i].split("\t");
        for(j = 0; j < rowlist.length; j++)
        {
            // ignores the current row
            if(i == j) 
            {
                continue;
            }
            s2 = rowlist[j].split("\t");
            if( s1[1] > s2[1] )
            {

            }
            else if( s1[1] < s2[1] )
            {
            }
            else 
            {
            }           
        }
    }   
    return newrowlist;  
}
</script>

对于上面的示例,函数应返回:

['1[TAB]AFG[TAB]3,416', 
 '2[TAB]BRA[TAB]2,073',
 '3[TAB]AUS[TAB]1,414',
 '4[TAB]JPN[TAB]1,316']

1 个答案:

答案 0 :(得分:0)

['AFG\t3,416', 'AUS\t1,414', 'BRA\t2,073', 'JPN\t1,316'].sort(function(a,b){
  //retrieving the rank by splitting the entry and return true or false to the sort callback function
  //in order to sort by rank 1,2,3 ...
  return(a.split('\t')[1]<b.split('\t')[1])
}).map(function(e,i){
  //creating a new array from the sorted array
  //adding the rank (using the index) - have to add 1, since index starts at 0
  return (i+1)+"\t"+e;
})