Attempting to find the total of the digits within a given string. For example, when the string is "99Hello1," the result should be 100, whereas for "9hello9," the correct sum is 18. Currently stumped by an unexpected error and unsure how

function NumberSearch(str) {
    var arr = str.split("");
    var sum = 0;
    var twoDigit = [];
    var two;
    var res = [];
    var arrFormat = preProcess(arr);
    console.log(arrFormat);
    //this custom function obtains an array containing all numbers from the string
    function preProcess(ele) {
        for (var i = 0; i < ele.length; i++) {
            if (typeof ele[i] === 'number' && typeof ele[i + 1] === 'number') {
                twoDigit.push(ele[i], ele[i + 1]);
                two = twoDigit.join("");
                res.push(two);
            } else {
                if (typeof ele[i] === 'number' && typeof ele[i + 1] !== 
            'number') {
                    res.push(ele[i]);
                }
            }
        }
        return res;
    }
    for (var k = 0; k < arrFormat.length; k++) {
        sum = sum + arrFormat[k];
    }
    return sum;
}

console.log(NumberSearch("99Hello1"));

The approach I'm taking involves iterating through the string to gather all numeric values and then calculating their total.

Answer №1

To extract numbers and sum them up, you might want to consider using a regular expression along with the reduce method on an array.

function calculateTotalNumbers(str) {
    return (str.match(/\d+/g) || []).reduce(function (accumulator, currentValue) { return accumulator + +currentValue; }, 0)
}

console.log(['99hello1', '9hello9'].map(calculateTotalNumbers));

Answer №2

For this task, you have the option to execute it using just one reducing stage.

let result = Array.prototype.reduce.call("99Hello9", (acc,char) => isNaN(+char) ? acc : +char+acc, 0);
console.log(result);

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

Adjusting solely the numeric values within a combined array containing both associative and numerical elements

When I send an SQL query to a table in my program, it returns a resource that I use the function mysql_fetch_array() on. The first argument is the results resource from the SQL query, but if you omit the next argument, it defaults to returning an array wit ...

Identifying the source object when using JSON.stringify

There is an object set up like this: { item1: "value1", item2: "value2", item3: { item4: "value4", item5: "value5" } } The goal is to utilize JSON.stringify along with a replacer function that behaves differently for items 4 & 5 ...

typescript: the modules with relational paths could not be located

As part of a migration process, I am currently converting code from JavaScript to TypeScript. In one of my files 'abc.ts', I need to import the 'xyz.css' file, which is located in the same directory. However, when I try to import it usi ...

Is it possible to utilize the three.js EventDispatcher for inter-class communication?

Main query I've encountered an issue where an event emitted on one class supporting EventDispatcher is not detected by another class also supporting EventDispatcher. How can I establish app-wide communication to efficiently pass messages between diff ...

Guide on generating virtual nodes from a string containing HTML tags using Vue 3

Investigation I stumbled upon this solution for converting a simple SVG with one path layer into Vue2 vnode list and wanted to adapt it for Vue3. After scouring resources, including the MDN docs, I couldn't find any pre-existing solutions. So, I dec ...

Use a function on values that have corresponding keys in a separate array

I am working with a form.value object that looks like this: form.value = { "to_date": "2019-03-21T05:00:00.000Z", "from_date": "2019-03-13T05:00:00.000Z", "is_form": "" "errors":"" } Additionally, I have an array called filterArray: filterArray ...

Processing the file to convert it into an array of integers

Currently, I am tackling HEVC specifically X265, and my focus is on inputting the QP array with values read from a file. It's important to note that these values range from 0 to 100. To test this process, I have set up a test file where I've inc ...

Challenge with Merging Bootstrap Clean Blog Template with React Application

I am facing difficulties while trying to merge the Bootstrap Clean Blog Template (Link Attached) into my React App. This template is available for free. After downloading the template, I created a new react project and moved all static assets & files ...

Resources for Vue.js stylesheets

Vue.js is my latest discovery and I have been experimenting with the single file component architecture. A small issue I encountered was that all of my components' styles were being loaded on the page, even if they weren't currently active. Is t ...

Tips for sending functions from client to server in Node.js

I'm working with this code snippet: const http = require('http'); const fs = require('fs'); const handleRequest = (request, response) => { response.writeHead(200, { 'Content-Type': 'text/html' ...

Component not displaying API data despite being visible in the console

Currently dealing with an issue where I am trying to make a simple API call to and then display the fetched data in my component. Strangely, the data is not showing up on the page, although it is being correctly displayed when I console log it. const Di ...

Iterate through a loop to remove DOM elements

I'm working on creating a loop that will be responsible for deleting DOM elements (one or more lines within an HTML table): <tr class="entireLine><input type="checkbox"></tr> <tr class="entireLine><input type="checkbox" che ...

How can I import a component directly from a webpack bundle in React?

Under normal circumstances, components are imported from another JavaScript file. However, in my project, I am looking to import a component from the webpack-created bundle. Step 1: Generate a bundle for the ABC folder, naming it abc.bundle.js Note: The ...

Challenges arising from the rendering of main.js in Vue.js

Recently, I started working with Vue and am now faced with the task of maintaining a project. Main.js contains the routing structure: Main.js import Vue from 'vue' const app = new Vue({ el: '#app', data: { message: & ...

Have Babel transpile configuration files into CommonJS format

I'm having trouble getting my Nuxt app to work with Jest for testing. I have a setupFilesAfterEnv property set with a setupTests.ts file that imports a translation file. The translations file uses ES6 import/export module syntax, but it seems like my ...

Is there a way to send a JSON object and a file to an ASP.NET server using the fetch method?

I'm facing a challenge here, as I attempt to send a json object from my indexedDb along with an IFormFile object to the server at the same time. The method that handles this scenario is structured like so: [HttpPost] public async Task<IActionR ...

Enhancing MongoDB within a MEAN (MongoDB, Express,

Looking for assistance in updating my MongoDB database? I have the server-side code ready, but need help implementing it on the client side using Angular. Can anyone provide guidance? module.exports.updateUser = function (req, res) { // Retrieve user wi ...

Retrieving the value of a hidden field in JavaScript following the execution of a PHP

I am facing an issue with my code. There is a JavaScript function on my page and a PHP function that populates a hidden field. However, when I try to retrieve the value of the hidden field from JavaScript, it does not seem to reflect the current value. It ...

What is the method used by Bootstrap to create a darker page background behind a modal?

I am struggling to understand how Bootstrap darkens the background of a page when a modal is displayed. Even though a class is added to the body tag (modal-open), the effect on the background isn't clear to me. Learn more about Bootstrap modals here ...

What is the correct way to assign the products variable to the array retrieved from the API response?

I am currently trying to implement a primeblocks component and I am struggling with v-binding the dataTable to the response I receive from my API. My issue lies in the fact that when I console.log(productData), I am getting an array that contains another ...