Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

javascript - Comparing sums of values inside array to determine which is the largest

I am working on a coding challenge and believe I am close to a solution, but am currently stuck and would appreciate some insight. I am trying to build a function that can take a set of numbers (credit card numbers including dashes), compare the sum of each number, and return the highest credit card number. The solution must utilize Javascript. The function is currently returning "undefined". Thanks in advance for any help!

function highestCredit(creditArray){
  var highSum = 0;
  var highIndex = 0;
  var sum= 0;
  //loop through each value in the array
  for (i = 0; i < creditArray.length; i++) {
    //loop that disregards dashes and adds up the sum of a single credit card number
    for (a = 0; a < creditArray[i.length]; a++) {
      if(isNaN(creditArray[i].charAt(a)) === false){
          sum += parseInt(creditArray[i].charAt(a));
      }
    }
    //compare current sum to highest sum, update the index if there is a new high number
    if (sum >= highSum) {
      highSum = sum;
      sum = 0;
      highIndex = i;
    }
  }
  return creditArray[i];
}

console.log(highestCredit(['4916‐2600‐1804‐0530', '4779‐252888‐3972', '4252‐278893‐7978' ,'4556‐ 4242‐9283‐2260']));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You had some errors, see working example

  function highestCredit(creditArray) {
    var highSum = 0;
    var highIndex = 0;
    var sum = 0;
    for (i = 0; i < creditArray.length; i++) {
        for (a = 0; a < creditArray[i].length; a++) { // error with length
            if (isNaN(creditArray[i].charAt(a)) === false) {
                sum += parseInt(creditArray[i].charAt(a), 10);
            }
        }
        if (sum >= highSum) {
            highSum = sum;
            sum = 0;
            highIndex = i;
        }
    }
    return creditArray[highIndex]; // should return 'highIndex', not 'i'
}

document.write(highestCredit(['4916‐2600‐1804‐0530', '4779‐252888‐3972', '4252‐278893‐7978' ,'4556‐ 4242‐9283‐2260']));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...