Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

javascript - Sorting 'numbers' with multiple decimal points

I've got a bunch of "numbers" that have multiple decimal points (so they're really strings). However, I want to sort them as if they were numbers.

1.1.1
10.2.3
2.6.7
21.10.4
3.10.12
4.11.5
4.1.16
6.4.23

I want them to sort by the first set of numbers (before the first decimal point), then by the second set, then by the third (with the possibility of it continuing for a fourth set or more). They should go in this order:

1.1.1
2.6.7
3.10.12
4.1.16
4.11.5
6.4.23
10.2.3
21.10.4

What is the best way to do this using JS? I'm thinking I'll probably need to break each number into an array, but there maybe a better way. Ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think something like this should do the trick:

nums.sort(function(a, b) {
    var nums1 = a.split(".");
    var nums2 = b.split(".");

    for (var i = 0; i < nums1.length; i++) {
        if (nums2[i]) { // assuming 5..2 is invalid
            if (nums1[i] !== nums2[i]) {
               return nums1[i] - nums2[i];   
            } // else continue
        } else {
            return 1; // no second number in b
        }
    }
    return -1; // was missing case b.len > a.len
});

Update heres a fiddle

When var nums = ['1.1.1', '2.6.7.3.2', '2.6.7', '2.6.7.3', '2.6.7.1', '6.4.23', '2.7']

Sorting this way => ['1.1.1','2.6.7.1','2.6.7.3.2','2.6.7','2.6.7.3','2.7','6.4.23']


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...