Seattle137
Seattle137

Reputation: 11

sum of integers in a string - JS

I am new to JS and am trying to find a solution to:

  1. I have an array with three phone numbers, I need to sum the integers of each phone number strings.

  2. Return the string (phone number) with the highest sum of digits.

I am embarrassed because I know so little in JS. I'm trying to get into school in the fall to learn. So far I have gotten through functions, for loops, and while loops.


var teach = ["111-222-3333", "333-444-5555", "959-232-8484"]

I know this next part is wrong but this all I have learned. can someone please help me?

var total = 0;    

for(var i = 0; i < teach.length; i++){
   total = total + Number(teach[i]);
}

alert(total);

Upvotes: 1

Views: 3120

Answers (3)

OSA413
OSA413

Reputation: 476

You can do this with a lot of chaining functions like this:

let integerSum = function(input) {
    return String(input).split("").map(s => Number(s)).filter(s => !isNaN(s)).reduce((a, b) => a + b, 0)
}

Upvotes: 0

Legotin
Legotin

Reputation: 2688

sumPhone calculates the sum of digits in a certain phone and maxPhone finds the maximum value.
replace( /\D/g, '' ) – removes all symbols of phone except digits.
split( '' ) – splits string of digits to array.
reduce(...) – sumarize the array. parseInt is needed to convert every digit to number.

var sumPhone = function( phone ) {
    return phone.replace( /\D/g, '' ).split( '' ).reduce( function( prev, current ) {
        return prev + parseInt( current );
    }, 0 );
};

var maxPhone = function( phones ) {
    var max_sum = 0,
        max_phone;

    phones.forEach( function( phone ) {
        var sum = sumPhone( phone );

        if ( max_sum < sum ) {
           max_sum = sum;
           max_phone = phone;
        }
    } );

    return max_phone;
};

maxPhone( ["111-222-3333", "333-444-5555", "959-232-8484"] );// returns "959-232-8484"

Upvotes: 1

Jack Guy
Jack Guy

Reputation: 8523

You were on your way. You need to go over each letter in the string.

var largestTotal = 0;
var largestPhoneNumber;

for (var i=0; i < teach.length; i++) {
   var phoneNumber = teach[i];
   var phoneNumberTotal = 0;

   for (var i=0; i < phoneNumber.length; i++) {
      phoneNumberTotal += Number(phoneNumber.charAt(i));
   }

   if (phoneNumberTotal > largestTotal) {
      largestPhoneNumber = phoneNumber;
   }
}

alert(largestPhoneNumber);

You can do that using .charAt(i) which will get the letter at a specified index, a bit like teach[i] accesses a specific element of that array.

Upvotes: 2

Related Questions