Transform the characters within a string into corresponding numerical values, calculate the total sum, and finally display both the sum and the original string

I'm looking to convert a string containing a name into numerical values for each character, ultimately finding the sum of all characters' numerical values. Currently, only the first character's value is being summed using .charAt(). To achieve this goal, I need to:

  1. Create a function with a loop to iterate through each character in the string.
  2. Implement conditionals to determine the numerical value of each character and aggregate it in the variable nameSum.
  3. Use console.log to display both the name and its corresponding numerical value.
  4. Handle cases of uppercase and lowercase letters later on.
  5. In the end, I aim to retrieve names from an array containing variables with strings as names.
   var name1 = 'bill';

const findNameVal = (name) => {
  let nameSum = 0;
  let cardCheck = name;
    for (let i=0; i < cardCheck.length; i++) {
        if (name1.charAt(i) === 'a') {
            return nameSum += 1; 
    } else if (name1.charAt(i)=== 'b') {
        return nameSum += 2;
    } else if (name1.charAt(i)=== 'i') {
        return nameSum += 9;
    } else if (name1.charAt(i)=== 'l') {
        return nameSum += 12;
    } 
}
}
console.log(`The name is: ${name1} and the numerical value is ${findNameVal(name1)}`);

Answer №1

Take a string and convert it into an array of lower-case characters. Then, use the reduce function to loop through each character in the array and retrieve its character code. For example, 'a'.charCodeAt() is 97, and 'b'.charCodeAt() is 98. By subtracting 96 from each code found, you can get the desired result:

var name1 = 'bill';

const findNameValue = (name) => {
  const lowercaseArray = [...name.toLowerCase()];
  return lowercaseArray.reduce((accumulator, char) => accumulator + char.charCodeAt() - 96, 0);
}
console.log(`The name is: ${name1} and its numerical value is ${findNameValue(name1)}`);

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

How many addresses are stored in the JSON file?

After verifying the JSON data and trying to determine the number of addresses, I encountered the following result when accessing the information: var location = req.body; The output obtained was: { AddressValidateRequest: { '-USERID': &ap ...

What is the best way to stylize a date using Bootstrap-datepicker?

While this topic is well-known, I have a slightly more complex question regarding it. I have gone through the documentation here. My goal is to display the date in French format (dd/mm/yyyy) and save the value in US format (yyyy-mm-dd). Additionally, I nee ...

A guide on updating a JSON object based on specific criteria

I'm dealing with two JSON files here - the first one is named origin.json, and the second one is called newData.json. My goal is to update the child value of Origin based on the data in NewData. However, I only want this update to impact items that a ...

What steps are involved in integrating OpenCV into a JavaScript project?

After recently installing OpenCV via npm using this guide: https://www.npmjs.com/package/opencv I'm facing a simple question. How can I actually utilize the OpenCV library in my project? The site provides a face detection example code snippet: cv.r ...

Navigating Tabs and jQuery for JSON Data Refresh: A Step-by-Step Guide

Struggling to implement a basic UI and seeking advice from the community. Here's my current setup: 1) Using getJSON to fetch a JSON string (multidimensional array) from a PHP page. 2) Utilizing 2 jQuery.each loops to iterate through the JSON data and ...

Tips for Looping through an Object within another Object

Is there a way to retrieve values from an Object that contains another Object nested inside? I am not overly concerned about the keys, but it would be helpful if I could access them as well. Here is an example of the response: res = {data: {name: 'na ...

Tips on obtaining the JSON format of an object containing an array variable

In my class, I have three variables including an array. I created a method specifically for use with json_encode(). public function getJSONString(){ return [ 'id' => $this->id, 'name' => $this->name, ...

Tips for retrieving the text value on keyboard enter press without triggering form submission

I am currently working on a feature where hitting the Enter key in a textbox should not automatically submit the form. The textbox is located within a form: @Html.TextBoxFor(model => model.ID, new { @class = "form-control input-sm", placehold ...

Utilize JSON text importing for template literals in Node.js

When it comes to my node js projects, I usually opt for using a text.json file and requiring it rather than hardcoding static text directly into my code. Here's an example: JSON file { "greet": "Hello world" } var text = require('./text.json ...

Display data in Highchart legend only if it has values

In a unique scenario, I am required to compare various items and display the results in a chart. The user inputs two, three, or four article IDs and receives the corresponding data displayed in a chart. The issue arises when the user enters only two or th ...

Retrieving text that has been HTML-escaped from a textarea using jQuery

Within my HTML file, I have a <textarea id="mytextarea"></textarea>. Suppose a user inputs the following text: <hello>, world! How can I retrieve res = "&lt;hello&gt;, world!"; based on the user's input? The current code s ...

Using the @ Symbol in Javascript ES6 Module Imports

One of the folders in my node_modules directory is called @mymodule, and within it, there is another folder named 'insidefolder'. The path to this folder looks like this: node_modules/@mymodule/insidefolder When trying to import insidefolder us ...

Tips for preloading a script in nextjs

I'm having trouble incorporating a script into my website. The issue is that the script doesn't load properly the first time the page loads, but after a few refreshes, it works and the responsible iFrame shows up. I've attempted several di ...

Transform the appearance of a button when focused by utilizing CSS exclusively or altering it dynamically

As a newcomer to coding, I am currently working on a project that involves changing the color of buttons when they are clicked. Specifically, I want it so that when one button is clicked, its color changes, and when another button next to it is clicked, th ...

Clicking on the ng-repeat will trigger the ng-click event, which populates all the data using ng

I need help including an HTML page using ng-click within ng-repeat. However, it is currently loading all the content for every ng-repeat element. My specific requirement is to only bind(ng-include) the clicked element. Please see the attachment for m ...

Guide to setting up sub-routes in fastify

Currently, I am incorporating fastify as the web framework for my nodejs project. My aim is to organize and call all routes from a specific directory while having a base route established in the main JS file, similar to how it's done in express. Despi ...

Having trouble receiving a response when making a request to an API

I encountered an issue while trying to fetch an API. Initially, I received an error message stating that the message port was closed before a response was received. After removing all extensions, the error disappeared but now I am still unable to receive a ...

Development of a custom waterfall toolbar design using MUI framework

I've been working with a setup similar to the one found here: https://codesandbox.io/s/1op5mqq9oq By clicking on the checkboxes, the <Toolbar /> is displayed. As you scroll down the page, the <Toolbar /> remains fixed at the top and even ...

Merge two arrays into a single array and assign keys to the elements

I've been grappling with this problem for quite some time. The challenge I'm facing involves merging two arrays. Here is the initial input: { "array_one": { "mrnreference": [ { "key_0": "18DK00310020B11A84" ...

My Discord bot seems to be malfunctioning and failing to send out

I am new to discord.js and I'm having trouble getting my bot to respond with a message when I send one on the server. The bot shows as online in Discord and "Logged in!" appears in the console when I run it, so client.on("ready") seems to be working f ...