Struggling to develop a Javascript function that identifies which element in an array of numbers (specifically phone numbers) has the highest sum? Despite feeling frustrated and defeated, I believe I am on the right track. Could someone provide some guidance on this? Below is the current state of my code:
function highest(inputArray) {
var sum = 0;
var currentHighest = 0;
var largest = 0;
Initial variables are set, followed by a for loop that goes through each element in the array.
for (a = 0; a < inputArray.length; a++)
var tempArray = inputArray[a].replace(/\D/g,'');
A temporary string is created to eliminate non-integers from the element, and a function sums up all the digits within it.
function sumDigits(str) {
for (i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i));
return sum;
}
}
An if statement is then used to determine if the current element's sum is equal to or greater than the highest sum.
if (sumDigits(tempArray) >= currentHighest) {
currentHighest = sum;
largest = inputArray[a];
return largest;
}
else {
return largest;
}
}
var newArray = ['123-456-7777', '963-481-7945', '111-222-3333'];
console.log(highest(newArray));
Here is the summarized code:
function highest(inputArray) {
var sum = 0;
var currentHighest = 0;
var largest = 0;
for (a = 0; a < inputArray.length; a++)
var tempArray = inputArray[a].replace(/\D/g,'');
function sumDigits(str) {
for (i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i));
return sum;
}
}
if (sumDigits(tempArray) >= currentHighest) {
currentHighest = sum;
largest = inputArray[a];
return largest;
}
else {
return largest;
}
}
}
var newArray = ['123-456-7777', '963-481-7945', '111-222-3333'];
console.log(highest(newArray));
When running the code, the output is "undefined". Any insights on that would be greatly appreciated. Thank you for your help.