Kage - 1 year ago 90
Javascript Question

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.

Changing your code with @nnnnnn suggestion, here is a demo:

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

var arr = [];

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

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);
}

var highest = 0;

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

console.log(arr[highest])``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download