找到最大的信用卡数组

时间:2017-01-01 05:10:39

标签: javascript

我有兴趣找到其数字总和为最大数字的信用卡号码。如果不止一个具有相同的最大数字总和,我希望列表中的最后一个具有该总和。

我正在尝试编写一个带有一个参数的函数。该论点将是一系列信用卡号码。假设数组可以有任意数量的信用卡号,每一个都是一串数字和短划线。该函数应返回具有最大数字总和的信用卡号。

这是我到目前为止所拥有的 -

function getSum(stringLength) {
    var stringLength = ['1476-0089-5132-7420', '2034-6002-3978-5567', '6647-1123-5895-0038'];
    var i;
    for (i = 0; i < stringLength; i++);
    for (string = 0; string < [3]; stringLength++);
    //stringLength + i =Sum ;

    if (0 > 1, 2) {
      return string(0);
    } else if (1 > 0, 2) {
      return string(1);
    } else(2 > 1, 0) {
      return string(2);
    }
    console.log('1476-0089-5132-7420', '2034-6002-3978-5567', '6647-      1123-5895-0038');
    console.log('The Larget Sum is:' + true);
  }
  /*criteria for code: Contain all variables and code needed within      a function.
  Have that function take one argument which will be an array of credit card number strings.
  Determine the sum of digits for each credit card number.
  Determine which credit card number has the last largest sum of digits.
  Use a return statement to return the required card number in its’ original form.*/

1 个答案:

答案 0 :(得分:0)

您可以尝试这种方法:

注意:;用于结束语句,因此当for(...);循环结束时,它不会执行任何操作。

&#13;
&#13;
var cardNos = ['1476-0089-5132-7420', '2034-6002-3978-5567', '6647-1123-5895-0038'];

var largestSum = cardNos.reduce(function(p,c){
  return Math.max(p, getSumOfDigits(c))
}, 0);

function getSumOfDigits(str){
  var s = str.replace(/[^0-9]/g, '').split("");
  return s.reduce(function(p,c){ return +p + +c});
}

console.log(largestSum);
&#13;
&#13;
&#13;