Sort with Number and String - does not sort to a number

Asked

Viewed 53 times

0

I have an array of objects like the below:

[ {"code":1,"name": "01 - teste um"},
  {"code":8,"name": "02 - teste dois"},
  {"code":32,"name": "209 - teste teste"} ...]

I need to sort this array by key name. Note that this key can be string only, "test" example, but it can also have a numeral on the front ("06 - test") with a hyphen/dash or a dot (07 . teste três).

The function I am using for sorting follows below.

var arrayOrdenado = array.sort(function( a, b ) { 
    var a_nome = a.name;
    var b_nome = b.name;
    if (a_nome && a_nome.indexOf(".")>-1){
        var a_nome = a_nome.substr(0, a_nome.indexOf("."));
        a_nome = parseFloat(a_nome);
    } else if (a_nome && a_nome.indexOf("-")>-1){
        var a_nome = a_nome.substr(0, a_nome.indexOf("-"));
        a_nome = parseFloat(a_nome);
    } 

    if (b_nome && b_nome.indexOf(".")>-1){
        var b_nome = b_nome.substr(0, b_nome.indexOf("."));
        b_nome = parseFloat(b_nome);
    } else if (b_nome && b_nome.indexOf("-")>-1){
        var b_nome = b_nome.substr(0, b_nome.indexOf("-"));
        b_nome = parseFloat(b_nome);
    }

    if ( a_nome < b_nome ) return -1;
    if ( a_nome > b_nome ) return 1;
    return 0;
});

The code orders correctly.

However, for the name "06 - test" gets out of order. The strange thing is that it only happens to the number 06.

I am not able to find the error, because as mentioned the array is ordered correctly except by the numeral "06".

  • It works for me: https://ideone.com/A0ibAw - Hunch: exist several different characters that are similar to the hyphen, it may be that in the case of "06" it has one of these characters, because there indexOf does not find it and 06 is not ordered by numerical value, see an example using "in Dash" (a "longer hyphen"): https://ideone.com/pDiY03

  • To find out if this is the problem, you can scroll through the characters of the string and print their codepoints (like https://ideone.com/pLiXLQ) - the hyphen Codepoint is 2d, if any different value appears in the place, it is because it is one of those other characters that I mentioned (and there the indexOf you won’t even find)

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.