Sort decimal notes

Asked

Viewed 70 times

3

I’m ordering a related json into notes in undescore.js

 {8.0 , 8,5 , 5,5 }

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

Punch the 10.0 he doesn’t throw up.. He gets like this

    8.8
    6.0
    5.5
    10.0
    0.0

How do I make him understand this?

  • 1

    this json is badly formatted, which is the oper? makes it clear?

  • 1

    Those notes are in string format, right? ('cause 10.0 > 5.5, but "10.0" < "5.5") Anyway, I do not understand why he is ordering in descending order instead of increasing, by the code shown should not give this result, whatever the type. Could give more details, for example a more complete code snippet?

  • Oper is json {note:8.0 , note:8.5 , note:5.5 } the notes are in json

  • correct mgibsonbr! is just add parseFloat() that resolvel, put as an answer for me to give as solved, thank you!

1 answer

6


Your problem seems to be that the notes are in string format, not numerical. String comparison is in lexicographic order, and how "1" < "5" then "10.0" < "5.5" (albeit numerically 10.0 > 5.5). Converting the data to number, as you yourself noticed, 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>

Browser other questions tagged

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