如何预先对数字进行排序而不是搞乱格式? [英] How do I pre-sort numbers and not screw up the formatting?
问题描述
function tester(col){
var rows = [//这会给我排序时的错误,所以将数字转换为字符串
[4,2,3,Tom],
[0,8,9,比尔],
[5,7,1,鲍勃],
[1,2,3,查理]
];
rows = [//将数字转换为字符串拧紧格式
[4,2,3,Tom],
[0 ,8,9,Bill],
[5,7,1,Bob],
[1,2 3,查理]
];
rows.sort(function(a,b){
return a [col] .localeCompare(b [col]); //按用户传递的列排序
});
返回行;
$ p如前所述,如果我传入数字,会出现一个错误: TypeError:在对象
$ b $中找不到函数localCompare b
如果我将这些数字转换为字符串,我可以排序,但用户无法格式化数字......显示更多小数点,逗号,将它们转换为百分比等。如何解决这是什么?
编辑:
我试过Buzinas / Kriggs的建议,但它似乎做了对数字和底片进行词汇排序,其他人排序不正确。我现在有(注意负4和750):
pre $ function tester(col){
var rows = [
[-4,2,3,Tom],
[0,8,9,Bill],
[5,750,1,Bob],
[1,2,3,Charlie]
];
rows.sort(function(a,b){
return a [col] .toString()。localeCompare(b [col] .toString());
} );
返回行;
UPDATE
既然你想按数字排序,如果它们是数字的话,如果它们是字符串,可以用字符串排序:
函数测试器(col){
var rows = [
[4,2,3,Tom],
[ 0,8,9,Bill],
[5,7,1,Bob],
[1,2,3,Charlie]
];
rows.sort(function(a,b){
if(typeof a [col] ==='number')
return a [col]> b [ col];
return a [col] .localeCompare(b [col]);
});
返回行;
}
I have a custom function I am writing that will return an array of arrays:
function tester(col){
var rows = [ // this gives me an error on sorting, so turn numbers to strings
[4,2,3,"Tom"],
[0,8,9,"Bill"],
[5,7,1,"Bob"],
[1,2,3,"Charlie"]
];
rows = [ // turning numbers to strings screws up formatting
["4","2","3","Tom"],
["0","8","9","Bill"],
["5","7","1","Bob"],
["1","2","3","Charlie"]
];
rows.sort(function(a, b) {
return a[col].localeCompare(b[col]); // sort by column passed by user
});
return rows;
}
As noted, if I pass in numbers I get an error:
TypeError: Cannot find function localCompare in object
If I turn those numbers into strings I can sort but then the user isn't able to format the numbers...show more decimals, commas, turn them into percentages, etc. How do I resolve this?
EDIT:
I've tried the suggestion by Buzinas/Kriggs but it seems to do a lexical sort for numbers and negatives and others don't sort properly. I now have (notice the negative 4 and 750):
function tester(col){
var rows = [
[-4,2,3,"Tom"],
[0,8,9,"Bill"],
[5,750,1,"Bob"],
[1,2,3,"Charlie"]
];
rows.sort(function(a, b) {
return a[col].toString().localeCompare(b[col].toString());
});
return rows;
}
UPDATE
Since you want to sort by number if they are numbers, and by string if they are strings, you can do:
function tester(col){
var rows = [
[4,2,3,"Tom"],
[0,8,9,"Bill"],
[5,7,1,"Bob"],
[1,2,3,"Charlie"]
];
rows.sort(function(a, b) {
if (typeof a[col] === 'number')
return a[col] > b[col];
return a[col].localeCompare(b[col]);
});
return rows;
}
这篇关于如何预先对数字进行排序而不是搞乱格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!