使用多个小数点对“数字”进行排序

编程入门 行业动态 更新时间:2024-10-10 22:20:10
本文介绍了使用多个小数点对“数字”进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一堆数字有多个小数点(所以它们真的是字符串)。但是,我想将它们分类为数字。

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

使用JS执行此操作的最佳方法是什么?我想我可能需要将每个数字分成一个数组,但也许有更好的方法。想法?

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?

推荐答案

我认为这样的事情可以解决问题:

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 });

更新 继承人

当 var nums = ['1.1.1',$ b时$ b'2.6.7.3.2','2.6.7','2.6.7.3','2.6.7.1','6.4.23', '2.7']

按此方式排序=> ['1.1.1','2.6 .7.1','2.6.7.3.2','2.6.7','2.6.7.3','2.7','6.4.23']

更多推荐

使用多个小数点对“数字”进行排序

本文发布于:2023-11-29 15:57:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646868.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   小数   点对   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!