Jonny Jonny - 3 months ago 9
Javascript Question

javascript sorting decimal numbers correctly

Ok I have a section of code that sorts the names it is given alphabetically.

However the code doesnt handle decimals the way I would want.

It orders the name in the following manner (Obv I would rather it incremented numerically):

It would order it:


  • APPLE - 1.0051

  • APPLE - 1.1071

  • APPLE - 11.1592

  • APPLE - 12.0692

  • APPLE - 12.1717

  • APPLE - 2.0186 << this should be after "APPLE - 1.1071" obviously

  • APPLE - 21.1407

  • APPLE - 22.089

  • APPLE - 23.069

  • BANANA - 1.0051

  • BANANA - 1.1071

  • BANANA - 11.1592

  • BANANA - 12.0692

  • BANANA - 12.1717

  • BANANA - 2.0186 << this should be after "BANANA - 1.1071" obviously

  • BANANA - 21.1407

  • BANANA - 22.089

  • BANANA - 23.069



Here is the code I am using. I do not fully understand the code as it was a snippet I have been using.

function(a, b){
var nameA=a.myname.toLowerCase(), nameB=b.myname.toLowerCase()
if (nameA < nameB) //sort string ascending
return -1
if (nameA > nameB)
return 1
return 0 //default return value (no sorting)
}


Regards,
Jonny

Answer

Demo and here is the source + small explanation:

function fruit_sort(a, b) {
    var parts = {
        a: a.split('-'),
        b: b.split('-')
    };
    if (parts.a[0] == parts.b[0]) // strings are the same
        return parseFloat(parts.a[1]) - parseFloat(parts.b[1]); // sort by number
    return parts.a[0] > parts.b[0] ? 1 : -1; // sort by string
}
var arr = ["APPLE - 1.0051",
    "APPLE - 1.1071",
    "APPLE - 11.1592",
    "APPLE - 12.0692",
    "BANANA - 1.0051",
    "BANANA - 1.1071",
    "BANANA - 11.1592",
    "BANANA - 12.0692",
    "BANANA - 12.1717",
    "APPLE - 12.1717",
    "APPLE - 2.0186",
    "APPLE - 21.1407",
    "BANANA - 23.069",
    "APPLE - 22.089",
    "APPLE - 23.069",
    "BANANA - 2.0186",
    "BANANA - 21.1407",
    "BANANA - 22.089"];
arr.sort(fruit_sort);
console.log(arr);
// outputs
[
    "APPLE - 1.0051",
    "APPLE - 1.1071",
    "APPLE - 2.0186",
    "APPLE - 11.1592",
    "APPLE - 12.0692",
    "APPLE - 12.1717",
    "APPLE - 21.1407",
    "APPLE - 22.089",
    "APPLE - 23.069",
    "BANANA - 1.0051",
    "BANANA - 1.1071",
    "BANANA - 2.0186",
    "BANANA - 11.1592",
    "BANANA - 12.0692",
    "BANANA - 12.1717",
    "BANANA - 21.1407",
    "BANANA - 22.089",
    "BANANA - 23.069"
]

First the function splits the terms up into their text and numerical parts - if the text is even it only sorts on the parseFloat value of the numerical value - otherwise it sorts first by the string value.

Comments