Bird Dad
Bird Dad

Reputation: 427

Return a piece of an array after finding the highest integer in java script?

So after working on finding the highest sum of any given amount of credit card numbers I realized I dug myself into a bit of a hole. (currently using 3 cards "123-123, 234-234 and 345-345" as test numbers.) After writing this out:

var howM = prompt("How many cards?")

var arr = [];

for(var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));

console.log(arr)

var sumpre = [];

for(var i = 0; i < howM; i++) {
  var sum = 0;
  var eXt = arr[i];
  eXt = eXt.replace (/-/g, "");
     for (var j = 0; j < eXt.length; j++) {
     sum += parseInt(eXt.substr(j, 1)); 
    }
  sumpre.push(sum);
}
console.log(sumpre);

var highest = sumpre[0];

for (var i=1; i<=sumpre.length; i++){
  if (sumpre[i]>highest){
    highest=sumpre[i];
  }
}

console.log(highest)

Which works to find the highest sum, however; I need it to return the card number with the highest sum in its original form at the end and am not sure what method would be best to get back to that or if I should reformat it from the start.

Upvotes: 1

Views: 71

Answers (2)

nnnnnn
nnnnnn

Reputation: 150080

As I mentioned in a comment, or as shown in Gerardo's answer, one way to do it with minimal changes to your current code is to use highest to keep the index of the array item with the highest value, instead of keeping the actual value itself - then you could retrieve the original card value via that index.

But for fun, here's another way to do it:

function sumDigitsInString(s) {
  return Array.prototype.reduce.call(s, function(p, c) { return p + (+c || 0); }, 0);
}

function itemWithLargestSum(a) {
  return a.reduce(function(p, c) {
    var sum = sumDigitsInString(c);
    return p[0] > sum ? p : [sum, c];
  }, [0])[1];
}

// given an array of strings:
var input = ["123-123", "234-234", "345-345", "111-111"];
var largest = itemWithLargestSum(input);
console.log(largest);

Further reading:

Upvotes: 1

Sreekanth
Sreekanth

Reputation: 3130

You could also do something like this, just with Array methods.

var inputCards = ["989-000", "123-999", "456-456"];
var sum = 0,
  sumNumbers = {},
  maxVal = 0;


inputCards.map(function(num) {
  var replaceText = new RegExp(/-/g);
  var number = num.replace(replaceText, "").split("");

  var prevVal = 0;
  sumNumbers[num] = number.reduce((prevVal, currentVal) =>
    parseInt(prevVal, 10) + parseInt(currentVal, 10));
});


console.log(Object.keys(sumNumbers).reduce((maxVal, currentVal) =>
  sumNumbers[maxVal] > sumNumbers[currentVal] ? maxVal : currentVal));

Upvotes: 0

Related Questions