gpt4 book ai didi

javascript - 按数字顺序对 "advanced"数字字符串进行排序

转载 作者:行者123 更新时间:2023-11-30 07:13:20 24 4
gpt4 key购买 nike

想象一下有这个数组:

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'
];

我如何使用 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']

I tried the following:

function mySort(a, b) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
}

但这只是输出:

["$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);


您可以通过使用保存总和的附加对象来加快该过程。

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


更新:由于您更新了问题,因此您需要比较各个部分。

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

关于javascript - 按数字顺序对 "advanced"数字字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42780497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com