JavaScript新手。下面是我的代码,下面是算法假设要完成的代码
function creditSum(arr) {
var num_of_elements = parseInt(arr)
array = arr.toString().split()
array = array.map(Number)
var sum_of_array = 0
for (var i = 0; i < num_of_elements; i++){
sum_of_array += array[i]
}
return sum_of_array
}
console.log(creditSum(['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260']))
对于此挑战,我们有兴趣找到其数字总和为最大数字的信用卡号。如果多个具有相同的最大数字总和,我们希望列表中的最后一个具有该总和。 编写一个带有一个参数的函数。该论点将是一系列信用卡号码。假设数组可以有任意数量的信用卡号,每一个都是一串数字和短划线。您的函数应返回具有最大数字位数的信用卡号。
以下是信用卡号码的示例数组:
['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260']
在上面的示例数组中,数字分别加起来为49, 81, 81, and 64
。由于有两个具有相同的总和,因此该函数应返回具有该总和的最后一个,在本例中为'4252-278893-7978'
答案 0 :(得分:0)
我认为应该这样做:
function creditSum(arr) {
const resultIndex = arr
.map(x => x
.split('')
.map(x => parseInt(x))
.filter(x => !isNaN(x))
.reduce((total, current) => total + current, 0)
)
.map((total, idx) => ({ idx, total }))
.sort((a, b) => b.total - a.total)
.reduce((result, current) =>
current.total >= result.total ? current : result,
{ total: 0 }
)
.idx;
return arr[resultIndex];
}
答案 1 :(得分:0)
这样做的原始方式。只是为了学习。我希望这能让你清楚地了解。
function creditSum(arr) {
var sum = [], current = 0, last = 0, w = 0;
//remove the dashed from the array item
for(var i = 0; i < arr.length; i++){
var newarr = arr[i].toString().split('-');
var x = newarr.length;
var s = 0;
//loop in from the new array of item after the split
for(var y = 0; y < x ; y++){
var ss = 0;
//get the sum of each digit
for(var z = 0 ; z < newarr[y].length; z++){
ss += parseInt(newarr[y][z]);
}
s += parseInt(ss);
}
//push it inside an array of sum
sum.push(s);
}
//check highest sum
for(var d = 0; d < sum.length; d++){
if(d == 0) { last = sum[0] };
current = sum[d];
if(last <= current){
w = d;
last = current;
}
}
return arr[w]
}
document.body.innerHTML = (creditSum(['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260']));
&#13;