[英]Sort array of strings with negative and positive numbers
Firstly I could not find a question addressing the whole issue. 首先,我无法找到解决整个问题的问题。
I used to compare arrays like this: 我曾经比较这样的数组:
array.sort((a, b) => {
return a.localeCompare(b, undefined, {numeric: true, sensitivity: 'base'})
})
But I realized it does not work on an array like ['a', 'A', 'B', -1.50', '0', '1.50', '-2', '2']
. 但我意识到它不适用于像
['a', 'A', 'B', -1.50', '0', '1.50', '-2', '2']
这样的数组。
The expected output would be: ['-2', '-1.50', '0', '1.50', '2', 'A', 'a', 'B']
. 预期输出将是:
['-2', '-1.50', '0', '1.50', '2', 'A', 'a', 'B']
。
I have some dirty ideas to achieve it. 我有一些肮脏的想法来实现它。 But maybe there is a clean and easy way.
但也许有一个干净简单的方法。
You could prepend the comparison by taking the delta of the wanted properties. 您可以通过获取所需属性的增量来预先进行比较。 This saves the order for numerical values.
这样可以保存数值的顺序。
console.log( ['a', 'A', 'B', '-1.50', '0', '1.50', '-2', '2', 'D'] .sort((a, b) => a - b || a.localeCompare(b, undefined, {sensitivity: 'base'})) );
numeric: true
option can be omitted for there won't be two numbers to compare at the left hand side of the expression. numeric: true
选项可以省略,因为在表达式的左侧不会有两个数字要比较。
You should use isNaN
method in order to check if you compare numerical strings. 您应该使用
isNaN
方法来检查是否比较数字字符串。 If yes, localeCompare
is not recommended , you need to use Number(a) - Number(b)
如果是,建议不要使用
localeCompare
,需要使用Number(a) - Number(b)
array = ['a', 'A', 'B','-1.50', '0', '1.50', '-2', '2'] array.sort((a, b) => { return !isNaN(a) && !isNaN(b) ? Number(a)-Number(b) : a.localeCompare(b, undefined, { sensitivity: 'base'}); }) console.log(array);
Since in Javascript the -
operator is defined only for numeric subtraction, the operands will be coerced to Number
. 因为在Javascript中
-
运算符仅定义为数字减法,所以操作数将被强制转换为Number
。 So you could simply use: 所以你可以简单地使用:
array.sort((a, b) => {
return a - b || a.localeCompare(b, undefined, { sensitivity: 'base'});
})
const customSort = (array) => {
return array.sort((a, b) => {
let r = /^-?\d+(?:\.\d+)?$/;
if (r.test(a) && r.test(b))
{
return a - b;
}
return a.localeCompare(b, undefined, {numeric: true, sensitivity: 'base'})
})
}
console.log(customSort(['a', 'A', 'B', '-1.50', '0', '1.50', '-2', '2']));
// => [ '-2', '-1.50', '0', '1.50', '2', 'a', 'A', 'B' ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.