Exploring arrays to find the maximum sum of elements

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.

Answer №1

If my understanding is correct (adding each digit of a phone number and then displaying the highest result), you can achieve this by following these steps:

//Create an array of phone numbers
var numbers = ['123-456-7777', '111-222-3333', '963-481-7945'];

//Using map to iterate through the array and calculate the sum of each number
var sums = numbers.map(function (m) {
    return {
        number: m,
        score: m.match(/\d/g).reduce(function (p, c) {
            return +p + +c;
        })
    }
}).sort(function (a, b) {
    if (a.score < b.score) return 1;
    if (a.score > b.score) return -1;
    return 0;
});

//Removing comments for brevity:
sums = numbers.map(function (m) {
    return {
        number: m,
        score: m.match(/\d/g).reduce(function (p, c) {
            return +p + +c;
        })
    }
}).sort(function (a, b) {
    if (a.score < b.score) return 1;
    if (a.score > b.score) return -1;
    return 0;
});

console.log(sums);

document.write("Number with the highest score: " + sums[0].number);
document.write("<br>");
document.write("Its score is " + sums[0].score);

This code snippet will display the phone number with the largest sum on the console. The total sum of digits can also be found in the returned object under the score property.

Answer №2

Your code lacks the initialization of the sum variable and you are prematurely returning the sum value in the provided function:

function sumDigits(str) {   
    for (i = 0; i < str.length; i++) {
        sum += parseInt(str.charAt(i));
        return sum;
    }
}

To correct this issue, the function should be adjusted as follows:

function sumDigits(str) {   
    var sum = 0;
    for (i = 0; i < str.length; i++) {
        sum += parseInt(str.charAt(i), 10);
    }
    return sum;
}

Without examining the entire code as a whole, it is challenging to identify other potential problems related to how various parts of the code are interconnected and interoperate.


For a more concise solution (assuming the goal is to sum the digits in each phone number):

var phoneNumbers = ["123-456-7890", "982-111-9999"];
var sums = phoneNumbers.map(function(p) {
    return p.match(/\d/g).reduce(function(sum, num) {
        return sum + parseInt(num, 10);
    }, 0);
});
var maxSum = Math.max.apply(Math, sums);

// display results in the snippet window                    
document.write("sums = " + JSON.stringify(sums) + "<br>");
document.write("maxSum = " + maxSum + "<br>");

Here is how this solution operates:

  1. Utilize .map() on the phone numbers array to generate an array of sums.
  2. Within the .map(), identify all digits, then execute .reduce() on the obtained array to accumulate the sum.
  3. For determining the maximum value in the sums array, utilize Math.max(), which can handle the entire array and determine the maximum value efficiently.

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

In Protractor, mastering the technique to extract multiple values simultaneously is crucial for efficiently handling applications that receive a large amount of push notifications

I am currently developing an automation test using Protractor for an application that receives a large volume of push notifications. The issue I am facing is testing a simple logic. expect(A + B).toEqual(C); The problem arises because A, B, and C are sou ...

When dynamically adding input fields in Bootstrap, there is a smaller gap between inline inputs

When adding a new list item dynamically in a modal using jQuery append, the spacing in the first li element seems to have a larger gap between the input fields compared to the rest that are added later. Even after checking the developer tools and confirmin ...

Error: Unrecognized HTML, CSS, or JavaScript code detected in template

I'm currently utilizing the "Custom HTML Tag" option in GTM with my code below, but encountering an error when attempting to publish: Invalid HTML, CSS, or JavaScript found in template. It seems that GTM may not support or recognize certain tag attri ...

Ways to establish a default search outcome in a search box

Looking to create a search bar with JavaScript and JSON to display default search results for visitors. Currently, the search bar only shows results after text is removed. How can I show predefined search results when the page is loaded? const search = ...

What is the most effective method for locating and modifying the initial instance of an element within a group?

In my Javascript/Typescript collection, I have the following items: [ {"order":1,"step":"abc:","status":true}, {"order":2,"step":"xyz","status":true}, {"order":3,"step":"dec","status":false}, {"order":4,"step":"pqr","status":false}, {"order":5,"step":" ...

Display HTML content using AJAX within a div element

Within my HTML code, I have the following: <li class="register"><a href="">Registreer</a></li> as well as <div id="content"> </div> I attempted to load an HTML file into the div using the code below in the header se ...

Interact with CakePHP using onKeyUp event

Hey there, I have a quick and easy question. I'm working with a textbox that needs to trigger a javascript/jquery function whenever it is typed into. <?= $this->Form->input('contract_prices.'.$num.'.quantity', [ 'id ...

I just stumbled upon Jupyter and I'm curious - can I utilize Javascript and store it in the cloud?

Yesterday evening, I stumbled upon Jupyter and began using it alongside Python. It seems like an excellent tool for coding, something that I've been in need of, but I'm not sure if I can integrate JavaScript with it. I noticed there are npm packa ...

I'm interested in developing a React function that generates recipe components based on a set of instructions provided in an array, along with a separate parameter specifying the recipe name

I am currently immersed in the book "Learning React" written by O'Reilly. The book mentions a method of creating components by using a function known as the "component creating function". It advises supplying the necessary parameters as the second par ...

Generate a new subprocess and terminate it once the operation has been initiated

Using child processes in the following way: var exec = require('child_process').exec; var cmd = 'npm install async --save'; exec(cmd, function(error, stdout, stderr) { console.log('stdout: ' + stdout); ...

What is the best way to determine the total number of rows that have been generated by the Asp:Repeater?

I'm looking for a way to retrieve the total number of rows generated by the repeater control using either Javascript or JQuery. Can anyone help me with this? ...

What is the best way to set up playwright-jest so that I can skip a specific Test Suite (spec) file during execution?

In my repository, I have a setup using `playwright-jest` with multiple spec files for test suites. I need to skip one of the spec files without moving it from its current directory in the repo. The default script in `package.json` is `"test": "jest -c jes ...

The length function appears to be signaling an unanticipated error

Recently, I encountered an issue with the code execution. Although the code appears to be functioning correctly, it is throwing an uncaught error. Is there a reason for concern regarding this situation? var xmlhttp = new XMLHttpRequest(); xmlhttp.onread ...

Displaying a webpage with a link using express.js

What is the process of rendering a page in express.js routes while including the anchor tag? For example: website.com/route#id-of-html-element ...

What could be causing axios to not function properly when used with async/await in this particular scenario

I need to update the DoorState when a button is clicked. After sending a request to the API to change the DoorState, I then call another API to check the status of the robot. Even though the DoorState has been successfully changed, it seems that the chan ...

Struggling with implementing a personalized zoom feature in React-Leaflet?

Looking to create a custom Zoom button using react-leaflet Below is the code I have been working on: import React from 'react'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import { Map, TileLayer } from 're ...

Steps for Disabling Autocomplete in a JSP Page

How can I prevent the browser from remembering the username and password on my JSP page after submitting the form? I've already tried using autocomplete=off in the JSP code. <form name="indexFrm" id="indexFrm" autocomplete="off" method="post"> ...

Using Angular's $post method to communicate with PHP CodeIgniter for making requests and handling responses

I am having trouble sending data from Angular to Codeigniter using $post. Here is the JavaScript code I am using: $scope.user.first_name = 'first name'; $scope.user.last_name = 'last name'; $http({ method: 'POST', ...

Updating object properties in Typescript

I have written the following Angular 2 TypeScript code: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) ...

There is no matching overload for this call in React Native

I am working on organizing the styles for elements in order to enhance readability. Here is the code I have written: let styles={ search:{ container:{ position:"absolute", top:0, }, } } After defining the s ...