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

Is it possible to implement hierarchical validation within reactflow nodes?

I am currently utilizing reactflow to establish a network of sequences, each possessing their own unique "levels." My primary objective is to restrict connections between sequences based on their respective levels. For instance, a level 5 sequence should ...

How can I show the number of items in my filtered data using AngularJS?

My data array holds objects in JSON format. var users = { 'New':{ {Name:'One'}, {Name:'Two'} }, 'Old':{ {Name:'Three'}, {Name:'Four'} } This piece of code is used to disp ...

What are the steps to ensure the effective functioning of my checkbox filter?

Currently, my product list is dynamically created using jQuery. I now need to implement filtering based on attributes such as color, size, and price. I found some code that filters the list items by their classes, which worked perfectly for someone else. ...

Utilizing onClick to target data within a .map function

I am struggling with the code provided below: const test = (e) => { console.log('example:', e.target.item.attributes.dataIWant); } {records.map((item, index) => { return ( <> <Accordion key={index} ...

Converting Callbacks to Promises in Node.js

I am facing a challenge with my node js application as I am attempting to promisify multiple callback functions without success. It has reached a point where I am unsure if it is even feasible. If you can assist me in promisifying the code provided below, ...

Design a logo to serve as the main button on the navigation bar of the

I've been experimenting with adding a logo instead of the 'Home' text in my navigation bar, but I'm not sure where to implement it. Should I add it within #nav or separately? Also, I want the nav bar to stay fixed without overlapping on ...

Retrieve an element generated by a React script without using the ref attribute

There is a chat button on my website generated by a script (zendesk chat) that creates an iframe with the ID "launcher". I am using Nextjs and I am trying to access this element, but I am unable to attach a ref since I do not have the code. I have been sea ...

When using React.js with Leaflet, ensure that the useEffect hook is only run on Mount when in the

I have encountered an issue where I need to ensure that the useEffect Hook in React runs only once. This is mainly because I am initializing a leaflet.js map that should not be initialized more than once. However, anytime I make changes to the component&a ...

Using JavaScript to empty input field when switching focus between input fields

I am experiencing an issue with clearing a input number field. Here is the code snippet in question: <input class="quantity_container" v-model="length.quantity" type="number" pattern="[0-9]*" inputmode="numeric" onfocus="if (this.value == &ap ...

Can anyone tell me where to find the unminified version of Bootstrap 3's docs.min.js file?

Could someone please provide me with the original version of this file? I've been trying to search for it in the project but haven't had any luck. You can find it here: https://github.com/twbs/bootstrap/blob/master/docs/assets/js/docs.min.js. ...

Guide on setting up and customizing run.json within the latest JetBrains Fleet for Next.js

I've been attempting to set up input/output for the latest IDE from JetBrains, Fleet. However, I've hit a roadblock and can't seem to figure it out on my own. That's why I'm turning to the Stack Overflow community for help - how do ...

What methods can I utilize to expand the qix color library with personalized manipulation features?

Utilizing the qix color library, my goal is to create specific custom manipulation functions for use in a theme. The approach I am taking looks something like this: import Color from 'color'; const primary = Color.rgb(34, 150, 168); const get ...

JavaScript/DOM - What sets apart a "CSS Selector" from an attribute?

When it comes to excluding declarative event handlers: <a href='#' onclick=<handler> ... /> Is there a significant difference between an Attribute and a CSS Selector? For example, if I define my own attribute: <a href='#&a ...

Storing multiple strings in a string array in Angular2

Hi everyone, I’m just getting started with Angular and currently working on creating a recipe page that fetches data from an API. The API setup is complete, but now I need to figure out how to input the data into the API using Angular. I have defined a ...

Rotating images on a canvas

We're currently implementing Ionic and Angular in our project. One issue we are facing is regarding image rotation on canvas. When we click on an image, the rotation works perfectly if it's a jpg file. However, when we pass a base64 image, the r ...

Deactivate certain days in Material UI calendar component within a React application

Currently, my DatePicker component in React js is utilizing material-ui v0.20.0. <Field name='appointmentDate' label="Select Date" component={this.renderDatePicker} /> renderDatePicker = ({ input, label, meta: { touched, error ...

The callback function fails to execute the click event following the .load() method

Hey there, I've hit a roadblock and could really use some help figuring out where I went wrong. Let me break down my script for you. On page1.html, I have a div that gets replaced by another div from page2.html using jQuery's .load() method. Here ...

Exploring Laravel's method for retrieving data from multiple tables in the controller

In an effort to make my jQuery call more dynamic, I have a controller with the following method: public function api(Request $request , $project_id){ return Program::where('project_id',$project_id)->get(); } This results in: [{"id":178," ...

Step-by-step guide on setting up a click counter that securely stores data in a text file, even after the

Can anyone help me make this link actually function as intended? Right now it only runs the JavaScript code, but I would like it to run the code and redirect to a webpage. Additionally, I need the data to be saved to a text file. Please provide assistanc ...

Guide to inputting text into the Dev element

I am encountering a challenge with automating gist creation on GitHub. The issue arises when trying to input text into the gist content-box (see attached image). Despite attempting to use Javascript executer, I have not been successful. JavascriptExecutor ...