Is there a lack of impact from using "continue" in a for loop

As a novice, I am trying to tackle this challenging kata:

This particular kata requires you to take a string and replace each letter with its corresponding position in the alphabet.

If there are any characters in the text that are not letters, simply ignore them and do not include them in the result.

"a" = 1, "b" = 2, and so on.

Although my solution works well until it encounters a whitespace within the string, which then gets included as an element in the positions array. I understand that filtering out the whitespaces could resolve this issue, but I would really like to understand why my code is failing.

function alphabetPosition(text) {
  const alphabet="abcdefghijklmnopqrstuvwxyz".split('');
  const letters = text.toLowerCase().split('');
  let positions =[];
  for (i=0; i<letters.length; i++){
    if (!(alphabet.includes(letters[i]))){
      continue;
      }
      positions[i]=(alphabet.indexOf(letters[i])+1);          
    }
  return (positions.join(' '));  
}

I believed that using continue should skip over the whitespaces within the letters array, but it seems that the continue keyword does not have the expected effect. I have tried researching the correct usage of continue, without finding where I went wrong. Any guidance or assistance would be greatly appreciated. Thank you in advance!

Answer №1

Though the continue command does allow for skipping subsequent commands within a loop, it is crucial to note that the loop counter i continues to increment regardless. This can lead to gaps in indexes when utilizing positions with indices, particularly evident when employing join.

To circumvent these discrepancies, consider utilizing push() to construct the positions array without relying on indexes.

for (i=0; i<letters.length; i++){
    if (!(alphabet.includes(letters[i]))){
        continue;
    }
    positions.push(alphabet.indexOf(letters[i])+1);          
}

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

showing a fading-in effect after a successful AJAX post

Maybe a simple question, but I've been struggling to make this work for quite some time now. Despite trying various solutions from stackoverflow, I can't seem to get it right. Perhaps fresh eyes could help me figure out how to achieve this. My g ...

Utilize jQuery to toggle classes on multiple elements in web development

I've been struggling to streamline this code I created for the website's navigation. As a novice in Javascript and jQuery, I would appreciate any help or advice. Thank you! Since the page doesn't reload, I have implemented the following met ...

Ways to alter the color of an icon when hovering over it

Is there a way to change the color of a material icon inside an IconButton material component when hovering over the IconButton? I've tried adding a class directly to the icon, but it only works when hovering over the icon itself and not the IconButto ...

Tips for resetting an RXJS scan operator depending on a different Observable

I created a component that triggers an onScrollEnd event once the last item in a virtual list is displayed. This event initiates a new API request to fetch the next page and combine it with the previous results using the scan operator. In addition, this c ...

What is the process for determining the vertex position of geometry in three.js after applying translate, rotate, and scale transformations?

I've recently delved into the world of three.js. My current goal involves creating a curve within the scene and subsequently applying some transformations to it. The function responsible for generating the line is showcased below: var random_degree ...

Is it possible to dynamically alter the color of a span text over a specific period of time?

Within my span tag, I am displaying text dynamically over a specific duration by reading a webvtt file. However, I want to change the color of the text during this given duration. I attempted to achieve this using CSS with transitions and passing the dura ...

What causes my Bootstrap 5 popover to no longer open on focus when I reopen the modal it is attached to?

I am facing an issue with my Bootstrap 5 modal and the popovers that are attached to it. On hovering over a button in my HTML, a popover appears asking 'Are you sure?' and instructing the user to click the button to proceed. Clicking the button ...

Timing with Three.js - the key to engaging interactive experiences

Lately, I've been discovering some amazing interactive shorts created with three.js. Take a look at this example: I'm curious about the timing mechanism used in these creations. Are there any known libraries for that? The synchronization of mu ...

How can I pass an array as input in a Rails form?

                My question is regarding an array referred to as:   params[:search][:cars] which currently holds the values: "search"=>{"cars"=>["11", "7"]} I am attempting to pass this array into a hidden form field using the following ...

Rotate the cylinder according to the normal vector of the tube endpoint

I'm working on creating a curved 3D arrow using three.js. My approach involves using a Tube along a curved path and a Cone shaped cylinder. Here's how they currently look: https://i.sstatic.net/jmVB6.png https://i.sstatic.net/P756z.png My goal ...

What is the best way to incorporate a vanilla javascript function into a vue.js application?

Consider a vanilla JavaScript function like this: if (window.devicePixelRatio >= 2) { document.querySelectorAll('img.retina').forEach(function (e) { let parts = e.src.split('.'); let ext = parts.pop(); i ...

Error: Attempting to create a Discord bot results in a TypeError because the property 'id' is undefined

While working on a basic Discord bot, I encountered an issue when running the -setcaps command. The error message I received was: TypeError: Cannot read property 'id' of undefined. I'm unsure about what might be causing this error. Any a ...

performing regular expression replacements in Node.js

In my Node.js code, I have the following string: var textToReplace = "Your <b class =\"b_1\">1</b> payment due is $4000.Your <b class =\"b_1\">2</b> payment due is $3500. Your <b class =\"b_1\"> ...

Transfer numerical values from PHP to JavaScript using individual files

What is the best way to pass variables from PHP to JavaScript when they are in separate files? Is it possible to achieve this without using AJAX, or is AJAX necessary for this task? If AJAX is required, how can I implement it? test.php <?php $a = 5; $ ...

Controlling submit button activation with jQuery through date restrictions

I have searched extensively but did not come across anything like this. I am looking to implement a feature that disables/enables the submit button based on specific dates. For instance, I want the submit button to be disabled on weekends and enabled on w ...

Is it necessary for services in Domain Driven Design to have knowledge of other services, or should they be aware of multiple repositories

As I work on developing a backend application, my focus is on implementing the Domain Driven Design. However, there's a particular question I have regarding the data structure that requires some clarification. Database Configuration Users Id ( ...

Pause until the array is populated before displaying the components

Currently, I am using firebase storage to fetch a list of directories. Once this fetching process is complete, I want to return a list of Project components that will be rendered with the retrieved directory names. How can I wait for the fetching to finish ...

Struggling to delete a specific item by its ID from MongoDB within a Next.js application

Currently, I am building a todo app in nextjs to enhance my skills. However, I'm encountering some difficulties in deleting single todos from the database using the deleteOne function. Below is the frontend call: async function deleteTodo(id) { a ...

Arrange an array of objects by two characteristics, with the priority given to one over the other

I have a collection of objects that look like this: // items: [ {type: 'FRUIT', description: 'Apple'}, {type: 'VEGETABLE', description: 'Carrot'}, {type: 'FRUIT', description: 'Banana'}, ...

Tips for transforming an anonymous function into a standard function with the utilization of the $variable keyword

I am struggling to convert the array_map section with the anonymous function into a regular function while still using the use function to support php 5.2. However, I keep encountering an error when attempting to do so. Below is my current code. <?php ...