Adding up whole numbers from a string - JavaScript

JavaScript is still very new to me and I'm facing a challenge:

  1. I have an array containing three phone numbers, and I need to calculate the sum of the digits in each phone number string.

  2. I want to find and return the phone number with the highest sum of digits.

I'm feeling a bit embarrassed because my knowledge of JavaScript is quite limited. However, I am determined to learn more and have plans to enroll in a school program this fall. So far, I've covered functions, for loops, and while loops.


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

I understand that my approach is incorrect, but this is all I know for now. Can someone please guide me on how to solve this?

var total = 0;    

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

alert(total);

Answer №1

You were making progress. Take the time to review each character in the string.

var highestSum = 0;
var highestNumber;

for (var i=0; i < collection.length; i++) {
   var number = collection[i];
   var total = 0;

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

   if (total > highestSum) {
      highestNumber = number;
   }
}

alert(highestNumber);

You can accomplish this by using .charAt(i) to retrieve the character at a specific index, similar to how collection[i] accesses a specific element in the array.

Answer №2

calculateSum computes the total sum of digits in a given phone number, while findMax identifies the phone number with the highest sum.
removeNonDigits( /\D/g, '' ) – eliminates all non-digit symbols from the phone number.
splitDigits( '' ) – breaks down the string of digits into an array.
aggregate(...) – combines the elements of the array. Utilize parseInt to convert each digit to a number.

var calculateSum = function( phoneNumber ) {
    return phoneNumber.replace( /\D/g, '' ).split( '' ).reduce( function( previous, current ) {
        return previous + parseInt( current );
    }, 0 );
};

var findMax = function( phoneNumbers ) {
    var highestSum = 0,
        maxPhoneNumber;

    phoneNumbers.forEach( function( phoneNumber ) {
        var sum = calculateSum( phoneNumber );

        if ( highestSum < sum ) {
           highestSum = sum;
           maxPhoneNumber = phoneNumber;
        }
    } );

    return maxPhoneNumber;
};

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

Answer №3

Here is one way to achieve this using a series of function chaining:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating horizontally within a list using Sencha Touch2

I currently have a list set up with the following configuration: var grid = Ext.create('Ext.List', { scrollable: { direction: 'horizontal', directionLock: true }, store: compStore, i ...

What is the process for translating symbols in a URL or text into hexadecimal characters? (e.g. changing = to %3D)

Currently, my script in use is extracting variables from URL parameters using jQuery. The value it retrieves happens to be a URL. For instance, if the URL is as follows: http://localhost/index.html?url=http://www.example.com/index.php?something=some the ...

Encase a group of child elements within a parent container using

Currently, I am able to wrap an entire li-element in an ordered list with a link: $(e).wrap('<a href="#" onclick="window.open(\'/xyz/\');return false;"></a>'); This is the HTML construct: <li class=""> ...

Utilizing Async.each fails to trigger the ultimate callback function

Here's the scenario: I expect the function finalCallBack to be triggered after we finish looping through all elements. var rows = [ { name: 'first'}, { name: 'second'} ]; var execForEachRow = function(row, callback){ var ...

store JSON data within an HTML list element

I've been working on a JavaScript script that allows me to generate list items in HTML. Right now, I have functionality to drag and remove the items using another script. However, I am interested in adding some additional information to each list item ...

How to use jQuery to hide list items after a certain threshold

$('li[data-number=4]').after().hide(); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li data-number="0"">1</li> <li data-number="1">2</li> ...

Rotating an object in Three.js along the radius of a sphere

I want to position an object at the end of a sphere's radius based on its coordinates (x, y, z). In traditional mathematical formulas for the coordinates of a point on a sphere, we use: var x = radius * Math.cos(phi) * Math.cos(theta); var y = radiu ...

Deactivate all functions of a complete row in the table

I'm working with a table that contains various user interaction controls in its cells, such as buttons and links. I'm looking to gray out certain rows of the table so that all operations related to those rows are disabled. Does anyone have sugge ...

creating a fresh window using AJAX in Ext JS

While I know there may be similar questions out there, the details of my situation are unique. I'm facing an issue with building a new window using ExtJS, starting from a pre-existing grid. The goal is to populate this new window with references to el ...

JQuery does not immediately update the input value

I'm working on a jQuery placeholder that mimics the behavior of default placeholders in Chrome and Firefox for browsers that don't support it. However, I'm facing an issue where the placeholder div's HTML doesn't change as quickly ...

What is the best way to extract the text from the first visible `<td></td>` table row using jQuery?

In this particular scenario, there is a table included: <table id="table"> <thead> <tr> <th>Name</th> <th>Course</th> </tr> </thead> <tbody> <tr style="display:none"> ...

Brochure displaying shattered tiles using ionic

Whenever I try to load a map using Ionic, it keeps displaying broken tiles. No matter if I load directly from Leaflet or use bower, the issue persists. Even when using pure leaflet code without any special directives, those broken tiles are still there. ...

Updating the state of a React Component using data from 2 input fields

I am facing an issue with two input fields of type "file" in a React component. My goal is to load a JSON file into each input field, save the data from both files into separate variables, and update the state of the component. However, I have noticed that ...

The issue I am facing involves a 404 not found axios error when attempting to send a post request

I am attempting to send data via a post request from react.js to express.js using axios, but I keep encountering a 404 not found axios error. You can view the error image here. Below is my code: export default function Upload() { const [state, setState ...

Delete the generated thumbnails from the input JavaScript file

One issue I'm facing is that I have written JavaScript code to generate a thumbnail when a user uploads an image. Now, I would like to implement a feature that allows the user to click on an "X" button to delete the uploaded image. This is the existi ...

A step-by-step guide to effectively stubbing a dependency within an express middleware using a combination of express-validator, mocha, chai, sinon,

**Edit: Re-created with a simple example that works first: I have an example file and two modules. moduleA has a dependency called moduleB // moduleA.js const ModuleB = require('./moduleB'); function functionA() { return 20 + ModuleB.functio ...

Prevent browser menus from opening by using JavaScript without triggering a new popup window

In seeking to safeguard the source code of my website, I am looking to prevent any unauthorized access. Therefore, I aim to deactivate all common methods of accessing the code such as Ctrl+U, Ctrl+Shift+I, F12, and browser menu options. ...

The issue of receiving a 404 error when attempting to send a string via Ajax

When a key is pressed and released, a JavaScript function is triggered. The function is supposed to call a controller action and return a result, but instead, I am receiving a 404 error. I have set breakpoints at the beginning of the controller action, but ...

an issue encountered while trying to print a webpage styled with CSS

Users are given the option to print the current page on the website by clicking on a menu element: <li> <a href="#" onClick="window.print()"> <i class="icon-print"></i> Print Page </a> </li> The page contai ...

Concealed Input Enhancements for AutoComplete

Hey there! I'm new to AJAX and could really use some help with my autocomplete function. I'm trying to store the ID of the user's selection in a hidden input field, but I've hit a roadblock. So far, my function isn't working as exp ...