nik*_*kop 1 javascript arrays sorting numeric
想象一下这个数组:
var fees = [
'$0.9 + $0.1',
'$20 + $2',
'$0.7 + $0.4',
'$5 + $0.5',
'$0 + $0.01',
'$100 + $9',
'$1 + $1',
'$2 + $0.5'
];
Run Code Online (Sandbox Code Playgroud)
如果使用vanilla JavaScript,我将如何按数字升序排序这些字符串值?
排序后所需的输出:
['$0 + $0.01', '$0.7 + $0.4', '$0.9 + $0.1', '$1 + $1', '$2 + $0.5', '$5 + $0.5', '$20 + $2', '$100 + $9']
我尝试了以下方法:
function mySort(a, b) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
}
Run Code Online (Sandbox Code Playgroud)
但这只是输出:
["$0 + $0.01", "$0.7 + $0.4", "$0.9 + $.1", "$1 + $1", "$100 + $9", "$2 + $0.5", "$20 + $2", "$5 + $0.5"]`
这可能是一个整洁和合乎逻辑的方式吗?
我不希望得到这笔钱,因为它会产生不必要的结果.考虑的例子"$0.9 + $0.1"和"$0.7 + $0.4"."$0.9 + $0.1"将是一个较低的值,因为总和是1,但我想排序,所以这"$0.7 + $0.4"是一个较低的值而不是.所以基本上希望对第一个数字进行排序,如果第一个数字在两个值之间相同,那么对第二个数字进行排序
根据字符串中的数字总和进行排序.
var fees = ['$0.9 + $.1', '$20 + $2', '$5 + $0.5', '$0 + $0.01', '$100 + $9', '$1 + $1', '$2 + $0.5'];
fees.sort(function(a, b) {
return getSum(a) - getSum(b);
})
function getSum(str) {
return str
// remove the $ and space
.replace(/[^\d+.]/g, '')
//split by + symbol
.split('+')
// get the sum
.reduce(function(sum, s) {
// parse and add with sum
return sum + (Number(s) || 0);
// set inital value as sum
}, 0)
}
console.log(fees);Run Code Online (Sandbox Code Playgroud)
您可以使用保存总和的其他对象来加快进程.
var fees = ['$0.9 + $.1', '$20 + $2', '$5 + $0.5', '$0 + $0.01', '$100 + $9', '$1 + $1', '$2 + $0.5'];
var ref = fees.reduce(function(obj, str) {
// define object property if not defined
obj[str] = str in obj || str
// remove the $ and space
.replace(/[^\d+.]/g, '')
//split by + symbol
.split('+')
// get the sum
.reduce(function(sum, s) {
// parse and add with sum
return sum + (Number(s) || 0);
// set inital value as sum
}, 0);
// return the object reference
return obj;
// set initial value as an empty objecct
}, {})
fees.sort(function(a, b) {
return ref[a] - ref[b];
})
console.log(fees);Run Code Online (Sandbox Code Playgroud)
更新:由于您已更新问题,因此需要比较各个部分.
var fees = ['$0.9 + $.1', '$20 + $2', '$5 + $0.5', '$0 + $0.01', '$100 + $9', '$1 + $1', '$2 + $0.5'];
fees.sort(function(a, b) {
// get numbers from a
var arrA = a.replace(/[^\d.+]/g, '').split('+');
// get numbers from b
var arrB = b.replace(/[^\d.+]/g, '').split('+');
// generate sort value
return arrA[0] - arrB[0] || arrA[1] - arrB[1];
})
console.log(fees);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53 次 |
| 最近记录: |