Word with the Most Points

I have created a code to determine the highest scoring word as a string, however when I calculate all words and attempt to display the results, I am encountering an issue where all results are showing as: NaN

function high(x) {
  var words = x.split(' ');
  var y;
  var num = [];
  for (var i = 0; i < words.length; i++) {
    y = words[i].split('');
    for (var d = 0; d < words[i].length; d++) {
      if (y[d] == 'a') num[i] += 1;
      else if (y[d] == 'b') num[i] += 2;
      ...
      // Similar conditional statements for letters up to 'z'
      ...
      else num[i] += 26;
    }
  }
  console.log(...num);
}

high("what time are we climbing up the volcano");

Answer №1

Make sure to initialize the variable num[i] first before attempting to perform addition with +=

function calculateValue(x) {
  var words = x.split(' ');
  var y;
  var num = [];
  for (var i = 0; i < words.length; i++) {
    y = words[i].split('');
    for (var d = 0; d < words[i].length; d++) {
      if (!num[i]) num[i] = 0; // <--- Ensure this line is added
      if (y[d] == 'a') num[i] += 1;
      else if (y[d] == 'b') num[i] += 2;
      else if (y[d] == 'c') num[i] += 3;
      else if (y[d] == 'd') num[i] += 4;
      else if (y[d] == 'e') num[i] += 5;
      else if (y[d] == 'f') num[i] += 6;
      else if (y[d] == 'g') num[i] += 7;
      else if (y[d] == 'h') num[i] += 8;
      else if (y[d] == 'i') num[i] += 9;
      else if (y[d] == 'j') num[i] += 10;
      else if (y[d] == 'k') num[i] += 11;
      else if (y[d] == 'l') num[i] += 12;
      else if (y[d] == 'm') num[i] += 13;
      else if (y[d] == 'n') num[i] += 14;
      else if (y[d] == 'o') num[i] += 15;
      else if (y[d] == 'p') num[i] += 16;
      else if (y[d] == 'q') num[i] += 17;
      else if (y[d] == 'r') num[i] += 18;
      else if (y[d] == 's') num[i] += 19;
      else if (y[d] == 't') num[i] += 20;
      else if (y[d] == 'u') num[i] += 21;
      else if (y[d] == 'v') num[i] += 22;
      else if (y[d] == 'w') num[i] += 23;
      else if (y[d] == 'x') num[i] += 24;
      else if (y[d] == 'y') num[i] += 25;
      else num[i] += 26;
    }
  }
  console.log(...num);
}

calculateValue("what time are we climbing up the volcano");

Answer №2

Ensure all array indices are initialized to 0 by utilizing Array(words.length).fill(0).

function calculateValues(x) {
  var words = x.split(' ');
  var y;
  var num = Array(words.length).fill(0);
  for (var i = 0; i < words.length; i++) {
    y = words[i].split('');
    for (var d = 0; d < words[i].length; d++) {
      switch(y[d]){
        case 'a':
          num[i] += 1;
          break;
        case 'b':
          num[i] += 2;
          break;
        case 'c':
          num[i] += 3;
          break;
            // Add more cases as needed
        default:
          num[i] += 26;
          break;
      }
    }
  }
  console.log(...num);
}

You also have the option to refactor your function like this:

function calculateValues(sentence) {
  const words = sentence.split(' ');
  const num = Array(words.length).fill(0);
  for (let i = 0; i < words.length; ++i) {
    const word = words[i];
    for (let j = 0; j < word.length; ++j) {
      num[i] += word.charCodeAt(j) - 96;
    }
  }
  console.log(...num);
}

calculateValues("what time are we climbing up the volcano");

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

Loop through JSON array within an angular controller

I am currently attempting to iterate through a JSON array and display the values on the frontend of my application. I have provided my code, but I'm having trouble retrieving specific values (startDate, endDate) from within the array and displaying th ...

Issue encountered while attempting to generate a Jquery button

I seem to be facing some difficulties as I have successfully completed this task before. Currently, I am dynamically adding HTML code: ...<td><label><input type=\"checkbox\" checked=\"checked\" class=\"Activechk fo ...

How can I ensure that I only include a field in a JavaScript object if the value is not null?

In my current setup, I am utilizing mongoose to write data to a MongoDB collection while ensuring there are no null fields. Default values have been set in the document for this purpose. During an update function call, certain fields may be null but I do n ...

Why does the Google Tag Manager noscript tag show up as a string when using react-gtm-module?

Implementing Google Tag Manager Tags in a React/Next.js app hosted on Netlify, I used the react-gtm-module. While the gtm script tag in the head section works perfectly, the noscript tag in the body is displaying an iframe as a string: <body> < ...

Having trouble with getting Express to automatically redirect to the main page upon user login

Currently, I am working on setting up a user login section. Despite the user_router successfully sending a JSON response, I am facing an issue with getting Express to send a new HTML page back to the client. The initial page offered is login.html, which co ...

The offlinefirst.sock encountered an EPERM error

Encountering an error when attempting to run https://github.com/jakearchibald/wittr on Windows bash. Assistance in either resolving or troubleshooting this issue would be greatly appreciated: Development server listening. (PID:469) Config server liste ...

Content in React Router may fail to load when refreshing the page, navigating forward, or manually

I recently started using React and I'm getting familiar with React Router. I divided my application into two main routes because each uses a different style: the Splash path is for when the user first enters, which contains the Splash screen, Login, a ...

Executing all promises later in Node.js using Promise.all

Having a series of promises set up as follows: module.exports = function (a, b, c) { return someAsync(() => { someFunc(a); }) .then(() => myPromises(a, b, c)) .then(result => { console.log(&apos ...

Verify whether the initial value is distinct from the subsequent one using AJAX

I'm currently working on a project where I need to compare the first value received from an AJAX call to the subsequent values. However, I seem to be stuck and unable to figure out how to achieve this. Every 5 seconds, I am checking the follower count ...

Apologies, but it seems there was an issue reading the "checked" property as it is null

I am currently facing an issue with the submit button in my Django application. It appears that the Javascript function is unable to determine which checkboxes are checked, as all I see in the console logs are "cannot read properties of null, reading "chec ...

AngularJS version 1.5.11 experiencing issues with ng-repeat functionality

Having an application built on angularJS v1.5.11, I encountered a major issue while attempting to use ng-repeat in a table format like below: <tbody> <tr ng-repeat="score in data.result"> <td ng-repeat="item in score"> {{ item }} & ...

Node.js server crashes upon automatic startup but remains stable when started manually

Currently, I am using Node.js and Socket.io to power an online chat feature. To manage the server, I have created a configuration file located at: /etc/init/example.conf The contents of this file are as follows: start on startup exec forever start /var/ ...

Encountered issue with Ajax post request without any additional details provided

I could really use some assistance with this issue. It's strange, as Chrome doesn't seem to have the same problem - only Firefox does. Whenever I submit the form, Ajax creates tasks without any issues. My MySQL queries are running smoothly and I& ...

Looking to disable the back button in the browser using next.js?

How can I prevent the browser's back button from working in next.js? // not blocked... Router.onRouteChangeStart = (url) => { return false; }; Does anyone know of a way to disable the browser's back button in next.js? ...

Can you guide me on how to programmatically set an option in an Angular 5 Material Select dropdown (mat-select) using typescript code?

I am currently working on implementing an Angular 5 Material Data Table with two filter options. One filter is a text input, while the other is a dropdown selection to filter based on a specific field value. The dropdown is implemented using a "mat-select" ...

Collaborate on global functions across the Quasar ecosystem and beyond, including Vue3

Is it plausible to utilize this method for sharing functionality (not data, which is handled by stores) in a Quasar and Vue3 application? // boot/generic_stuff.js import {boot} from 'quasar/wrappers' const function_list = { /* content goes here ...

In PHP, show the restore button if the status is 0; otherwise, display the delete button

I have a single button labeled "Delete." When the admin clicks on this button, the record is updated in the database and the button changes to "Restore," and vice versa. If the status of the record is 0, then the "Restore" button should be displayed. I a ...

What is the process of embedding base64 encoded data into an image in Javascript after retrieving the data from Azure Blob Storage?

I am attempting to insert an image by utilizing the base64 data pattern, rather than a URL link. Initially, I retrieve the data from Azure Blob storage using the Azure Node.js SDK: Azure Node.js SDK After downloading the data as a string, I am unsure of ...

Updating the title of a page on CoreUI's CBreadcrumbRouter dynamically

I'm currently developing a project with VueJS and the CoreUI admin template. Is there a way I can change the title of the current page as shown on the CBreadcrumbRouter? The GitHub documentation mentions that the script typically displays meta.label ...

Automating the selection of a drop down based on a condition in Angular 2: A step-by-step guide

I'm facing an issue with a drop-down menu where no default value is selected. On my homepage, I need to automatically select an option based on query parameters. I've attempted various methods but none have been successful. Below is the code snip ...