问题描述
我有兴趣查找数字总和最大的信用卡号.如果多个具有相同的最大数字总和,我希望列表中的最后一位具有该总和.
I am interested in finding the credit card number whose digits sum to the largest number. If more than one has the same largest sum of digits, I want the last one in the list with that sum.
我正在尝试编写一个带有一个参数的函数.该参数将是信用卡号的数组.假设该数组可以具有任意数量的信用卡号,并且每个信用卡号都是一串数字和破折号.该函数应返回数字总和最大的信用卡号.
I am trying to write a single function that takes one argument. That argument will be an array of credit card numbers. Assume the array can have any number of credit card numbers and each one is a string of digits and dashes. The function should return the credit card number that has the largest sum of digits.
这是我到目前为止所拥有的-
Here is what I have so far-
var creditCardNumbers = ['5865-2600-5889-0555', '4779-598666-3666', '4252-278553-7978' ,'4556-4242-9283-2260'];
var sums = creditCardNumbers.map(function(f) {
return f.match(/\d/g).reduce(function(sum, num) {
return sum + parseInt(num);
}, 1);
});
var maxSum = Math.max.apply(Math, sums);
console.log("totalSums = " + (sums) );
console.log("maxSum = " + maxSum );
console.log("Number with the highest sum: " + (sums.creditCardNumbers));
//This last console.log does not work
我无法退还最高金额的相应信用卡号.如果有人对如何解决此问题有任何建议,那用自己的方式是很棒的.预先感谢!
I am having trouble returning the corresponding credit card number with highest sum. If anyone has advice on how to achieve this problem their own way that's great. Thanks in advance!
推荐答案
您的代码可能看起来像这样
Your code might look like this
var ccn = ['5865-2600-5889-0555', '4779-598666-3666', '4252-278553-7978' ,'4556-4242-9283-2260'],
filtered = [],
ccnSums = ccn.map( e => Array.prototype.reduce.call(e.replace(/-/g,""), (p,c) => 1*p+1*c));
ccnSums.forEach((e,i,a) => a.lastIndexOf(e) == i && filtered.push(e));
因此从给定数据中它返回ccnSums
作为[77, 88, 74, 64]
,而filtered
也是[77、88、74、64],但是如果我将第三张信用卡号更改为'4255-278553-7978',它返回ccnSums
作为[77, 88, 77, 64]
,现在filtered
是[88, 77, 64]
.我希望这就是您想要的.
So from the given data it returns ccnSums
as [77, 88, 74, 64]
and filtered
is also [77, 88, 74, 64] however if i change the 3rd credit card no to '4255-278553-7978' then it returns ccnSums
as [77, 88, 77, 64]
and now the filtered
is [88, 77, 64]
. I hope this was what you wanted.
这篇关于在信用卡号数组中查找最大和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!