How to ignore “-” and “.” characters in a value during sort comparison?

独自空忆成欢 提交于 2019-12-24 07:27:22

问题


I have an html page that has a field that can be sorted. I also have created a javascript function that can sort that field in order. Let's imagine p_cSort is the 'id' name of that field.

function change_sort(neworder) {
 document.sortForm.p_cSort.value = neworder;
 document.sortForm.submit();

However when I have values like

12.34
12-35
12.36
12-33

and I search for them on my search page. The results returned are

12.34
12.36
12-33
12-35

How can I ignore the characters "." and "-" when sorting?

So the result I am looking for should be:

12-33
12.34
12-35
12.36

回答1:


Why don't you make a custom sort function liek this:

var x = ['12.5', '11.3', '13-5', '10-0'];
x.sort(function(a, b){
    a = a.replace(/[-]/, '.');
    b = b.replace(/[-]/, '.');
    if( parseInt(a) < parseInt(b) ) return -1;
    if( parseInt(a) > parseInt(b) ) return 1;
    return 0;
});

Output:

["10-0", "11.3", "12.5", "13-5"]

This will also work if you have 125.5 and so on. because the . and the - are both used in the compare.

Example with >= 100

So input:

["100-0", "11.3", "12.5", "13-5"]

Will output

["11.3", "12.5", "13-5", "100-0"]



回答2:


Short answer is using replace and sort function:

"12.34".replace(/[.-]/, '')

Full answer

var a = ["12.34", "12-35", "12.36", "12-33"];
var b = a.sort(function(a, b){
 return parseInt(a.replace(/[.-]/, '')) - parseInt(b.replace(/[.-]/, ''))
});
// now b contain sorted array
// ["12-33", "12.34", "12-35", "12.36"]


来源:https://stackoverflow.com/questions/22360440/how-to-ignore-and-characters-in-a-value-during-sort-comparison

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!