gpt4 book ai didi

javascript - 比较每个数值的总和后如何对数组元素进行排序和列出

转载 作者:行者123 更新时间:2023-11-28 05:45:13 25 4
gpt4 key购买 nike

此代码仅返回数值总和的顺序,如何返回按最大总和排列在顶部的列表中的数组元素?例如,结果应该是:

"1234-2722-2343-2842"
"1234-2722-2343-2345"
"1234-2322-2343-2342"

代码:

var addSum = function(ccNum) {
var sum = 0;
for (var i=0; i<ccNum.length; i++ ) {
var eachLetter = ccNum.charAt(i);
if (!isNaN(eachLetter)) {
sum += +eachLetter;
}
}
return sum;
};

var ccNums = ["1234-2322-2343-2342","1234-2722-2343-2345", "1234-2722-2343-2842"];

var checkNums = [];

for (var i=0; i<ccNums.length; i++) {
var ccNum = ccNums[i];
var sum = addSum(ccNum);
console.log("The checksum of CC number:"+ccNum+" is "+sum);
checkNums.push(sum);
}

checkNums.sort(function(a,b) {
return b-a;
});

console.log(checkNums);

最佳答案

使用String.replaceString.splitArray.mapArray.filter和的解决方案数组.reduce:

var ccNums = ["1234-2322-2343-2342","1234-2722-2343-2345", "1234-2722-2343-2842"],
getSum = function(num){
return num.replace("-", "").split("").map(Number).filter(Boolean).reduce(function(prev, next){
return prev + next;
});
};

ccNums.sort(function (a, b) {
return getSum(b) - getSum(a);
});

console.log(ccNums);

输出:

["1234-2722-2343-2842", "1234-2722-2343-2345", "1234-2322-2343-2342"]

关于javascript - 比较每个数值的总和后如何对数组元素进行排序和列出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38582131/

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