Search code examples
javascriptarrayssortingranking

Ranking an array of string rows by score


I need to create a new array of string rows from an input one. The input array contains just a country name followed by its score. My goal is to recreate this array by adding one more value, which is the rank that the country will appear. Please, check out my skeleton code below.

<!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>

For the example above, the function should return:

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

Solution

  • ['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;
    })