JSFiddle - React, Tailwind, and code Playground
JavaScript
var ccNumbers = ['1111', '888-222', '21-11', '9989', '9918'];
function addDigits(numbers) {
var sumArray = []; //store several sums to print
for (x = 0; x < numbers.length; x++) { //loop through ccNumbers array
var ccNmbr = numbers[x]; //pick out one array item and store it in ccNmbr
ccNmbr = ccNmbr.replace("-", 0);
ccNmbr = ccNmbr.replace(" ", 0);
let sum = 0;
for (y = 0; y < ccNmbr.length; y++) { //loop through each digit in ccNmbr
sum += parseInt(ccNmbr.charAt(y), 10); //add each digit to the sum
} //close adding digits loop
sumArray.push(sum); //add sum to an array
} //close looping through array loop
var largest = Math.max(...sumArray); //finds the largest added up number
let index = 0;
for (i = 0; i < sumArray.length; i++) {
if (largest === sumArray[i]) { //if there is a match... This isn't working. It matches itself.
index = i;
}
}
return ccNumbers[index];
}
alert(`The largest credit card number is ${addDigits(ccNumbers)}`);