JavaScript无法正确对十进制数进行排序 [英] Javascript not sorting DECIMAL numbers correctly

查看:95
本文介绍了JavaScript无法正确对十进制数进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码对按字母顺序给出的名称进行排序.
我遇到的问题是它处理小数的方式.
它按如下顺序排列名称(我希望按数字顺序递增):

I have some code that sorts names it is given alphabetically.
The problem I am having is with the way it handles decimals.
It orders the names like below (i would rather it increment numerically):

DOG - 1.0510
DOG - 1.1031
DOG - 11.1792
DOG - 12.0920
DOG - 12.1170
DOG - 2.0186 <-- should be after "DOG - 12.117" ???
DOG - 21.4070
DOG - 22.0790
DOG - 23.0390
CAT - 1.0810
CAT - 1.1071
CAT - 11.1592
CAT - 12.0691
CAT - 12.1718
CAT - 2.0186 <-- again should be after "CAT -12.1718" ???
CAT - 21.1403
CAT - 22.081
CAT - 23.069

我在一个对象数组中拥有名称/值,如下所示:

I have the name/values inside an array of objects like below:

var array = [
   {
      "myname":"DOG",
      "value":1.0051
   },
   {
      "myname":"DOG",
      "value":1.1071
   }
];

这是我在网上找到的摘录中使用的代码.

Here is the code I am using from a snippet I found online.

function(x, y){
             var xName=x.myname.toLowerCase(), yName=y.myname.toLowerCase()
             if (xName < yName) //string sort ascending
              return -1 
             if (xName < yName)
              return 1
             return 0 //return default value (without sorting)
        }

推荐答案

认为问题在于,您还需要按值排序,但仅按名称排序.
下面应解决此问题,先按字母顺序,然后按数字顺序.

Think the problem is that you need to sort by the value as well but you are only sorting by the name.
The below should fix it, it sorts alphabetically and then numerically.

代码:

function(x, y) {
    var parts = {
        x: x.myname.split(' - '),
        y: y.myname.split(' - ')
    };
    if (parts.x[0] == parts.y[0]) // strings are the same
        return parseFloat(parts.x[1]) - parseFloat(parts.y[1]); // sort by number
    return parts.x[0] > parts.y[0] ? 1 : -1; // sort by string
}

这篇关于JavaScript无法正确对十进制数进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆