Sort decimal notes

3

I am ordering a related json in notes in undescore.js

 {8.0 , 8,5 , 5,5 }

    var asc = _.sortBy(oper, function(num) {
                return num.nota;
            });

    8.8
    6.0
    5.5
    10.0
    0.0

How do I make him understand this?

    
asked by anonymous 31.03.2015 / 17:11

1 answer

6

Your problem seems to be that the notes are in string format, not numeric. The comparison of strings occurs in lexicographic order, and as% with% of% then% with of% (although numerically% with%). Converting the data to number, as you yourself realized, solves the problem:

var oper = [{nota:"8.8"}, {nota:"10.0"}, {nota:"6.0"}, {nota:"0.0"}, {nota:"5.5"}];

var asc = _.sortBy(oper, function(num) {
                return parseFloat(num.nota);
            });

document.body.innerHTML += "<pre>" + JSON.stringify(asc, null, 4) + "</pre>";
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"></script>
    
31.03.2015 / 17:31