The function fails to return any value, however console.log does output something

I am attempting to implement a JavaScript function that checks for repeated letters within a string. The goal is for the function to return false if any repeating letters are found, and true if no repeats are present. However, I am encountering an issue where the function does not provide a return value as expected. Essentially, I aim to compare two strings and output a boolean result based on their content.

function isIsogram(str) {
  let str1 = str.toLowerCase().split("");
  //console.log(str.toLowerCase())
  let str2 = []
  for (let i = 0; i < str1.length; i++) {
    //console.log(str1[i])
    if (str2.indexOf(str1[i]) === -1) {
      str2.push(str1[i])
    }
  }
  //console.log(str2)
  if (str2 === str1) {
    return true;
  } else return false;
}


console.log(isIsogram("abba"))

Answer №1

If you're looking to check for repeating characters in a string, you can use the following code snippet:

 function detectRepeatedChars(inputString){ 
     return inputString.split("").some(
            function(char,index,array){
                return array.lastIndexOf(char)!=index
            }
     );
 }

This solution is quite effective and easy to understand. Further details can be found here: Check for repeated characters in a string Javascript

Answer №2

One way to enhance the efficiency of your code is by implementing the following algorithm:

function checkIsogram(str) {
  let foundCharacters = [];
  
  for (let index = 0; index < str.length; index++) {
      const character = str[index];
      if (foundCharacters.includes(character)) {
          return false;
      }
      foundCharacters.push(character);
  }
  
  return true;
}


console.log(checkIsogram("abc"));
console.log(checkIsogram("abccba"));

Answer №3

Comparing two arrays is not a simple task. A workaround is to join them into strings first before comparing.

function checkIsogram(str) {
  let string1 = str.toLowerCase().split("");
  
  let string2 = []
  for (let i = 0; i < string1.length; i++) {
    
    if (string2.indexOf(string1[i]) === -1) {
      string2.push(string1[i])
    }
  }

  if (string2.join('') === string1.join('')) {
    return true;
  } else return false;
}


console.log(checkIsogram("abba"))

Alternatively, there's a simpler solution using the Set data structure.

function checkIsogram(str) {
  return new Set(str.split('')).size === str.length
}

console.log(checkIsogram("abba"), checkIsogram("abc"))

Answer №4

When comparing two arrays with characters in them, using str2 === str1 will not work as the strict equality operator, ===, is designed for primitive types such as strings or numbers, not arrays.

An easy solution in your code would be to convert both str1 and str2 to strings using the join method, and then compare them like this: str2.join('') === str1.join('').

To learn more about equality checks in JavaScript, visit this link. You can also find information about the join method here

P.S. - While this approach may not be the most optimal, it's a simple way to get started.

Answer №5

Here is my solution:

function checkIsogram(str) {
    let strArr = str.toLowerCase().split("");
    let uniqueChars = [];
    for (let j = 0; j < strArr.length; j++) {
        if (uniqueChars.indexOf(strArr[j]) === -1) {
            uniqueChars.push(strArr[j]);
        }
        else{
            return false;
        }
    }
    return true;
}


console.log(checkIsogram("hello")); // Should return false

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

Establishing a standard flatiron-director route (within the element) using the polymer core-pages component

This particular query is closely linked with issues surrounding the usage of flatiron-director/core-pages SPA in conjunction with route-specific JavaScript functions and default routes. While the solution proposed may be effective, my limited expertise in ...

Timer repeatedly triggered until nausea ensued (native v8natives.js:1582)

My website is running extremely slow and after conducting a test using the Timeline feature in Chrome Tools for Developers, I discovered that there is a Timer firing in a JS file called v8natives.js for about 9 seconds. After checking my Wordpress plugins, ...

Set up a custom JavaScript function to automatically refresh a webpage

I am in the process of setting up a JavaScript function to refresh on a specific webpage. The website utilizes an overarching JS and CSS framework, but I desire this particular function to load in a unique manner. The JS function within the framework dyna ...

jQuery Animation: Creative Menu Icon Display

Whenever the toggle menu's navigation icon is clicked, it triggers an animation that transforms the "hamburger" icon into an "X", causing the navigation menu to drop down. If a user clicks either the navigation icon or outside of the active toggle me ...

What's the best way to modify HTML element classes using Javascript?

I have designed a custom cms theme with various customization options that I wish to showcase in a live demo. My goal is to implement Javascript style switchers or modifiers where users can choose values from checkboxes or select tags, and see their select ...

What is the best way to attach an attribute to a element created dynamically in Angular2+?

After reviewing resources like this and this, I've run into issues trying to set attributes on dynamically generated elements within a custom component (<c-tabs>). Relevant Elements https://i.stack.imgur.com/9HoC2.png HTML <c-tabs #mainCom ...

Textfield removal from the input range is requested

I recently encountered an issue with my input range HTML code. Here is the initial code snippet: <input class="sliderNoTextbox" id="ti_monatlich" type="range" name="ti_monatlich" data-theme="d"> After some adjustments based on this helpful answer, ...

When using the setTimeout function to update the state, React useContext appears to be ineffective

As a newcomer to React, I have a question about refreshing the score in my card game within a forEach loop using setTimeout. While the state appears to update correctly, the DOM (Component overarching) does not reflect these changes. export function Refill ...

A step-by-step guide on crafting a customized archetype for nodeJs projects

Exploring the world of the node.js framework and looking to develop a template blueprint for node.js projects. The aim is to establish a set structure with essential folders and configuration files so that others can easily generate their own projects usin ...

What is the syntax for creating a link tag with interpolation in Angular 2 / Ionic 2?

As I work on developing an app using Ionic 2/Angular 2, I have encountered a challenge that I am struggling to overcome. Let me provide some context: I am retrieving multiple strings from a webservice, and some of these strings contain links. Here is an e ...

Steps to replace the content of an HTML file (such as modifying images) by clicking on an element in a separate HTML file

Currently, I am in the midst of a project and wondering if it is possible to dynamically modify the content of an HTML file, such as images and text, using JavaScript. My goal is to achieve this without relying on any frameworks, simply by clicking on el ...

React Native Child Component State Update Issue

In my code, there is a Child component that triggers a function in the Parent component. However, when the function is triggered, an error related to the setState method is thrown. Issue with Promise Rejection (id: 0): The '_this12.setState' i ...

How can I effectively organize an Angular2 component library for optimal efficiency?

Looking to develop an Angular2 datepicker component with the intention of releasing it and using it in multiple projects. Wondering about the best way to structure the project for this specific purpose compared to a typical Angular2 project created with an ...

Replacing text within nested elements

I am facing an issue with replacing certain elements on my webpage. The element in question looks like this: <div id="product-123"> <h3>${Title}</h3> <div> ${Description} </div> <div> ${P ...

Authenticate through navigation on an alternate component

I am in the process of developing a user interface that includes a side navigation and header bar. However, if the user is not logged in, I wish to redirect them to the login page. The primary component structure is as follows: class App extends Componen ...

What is the best way to handle an AJAX request within an if-else statement?

Attempting to utilize an if-else condition in order to make a jQuery Ajax call to an API. Having trouble understanding why the ajax function is being called even though it should be in the else statement. Below is the code snippet: if (e.value == null | ...

Troubleshooting a page refresh error displaying "file not found" when using [angular js + NodeJS/ExpressJS] - solving the

Note: In my attempt to solve all questions and answers related to this topic, I have encountered an issue. I am developing a web application using AngularJS with HTML5, NodeJS/ExpressJS, and MongoDB for the database. However, when trying to remove the &apo ...

Can one look through a div to the one beneath it by moving the cursor?

Hey there! I have a unique question for you. I've been trying to achieve a specific effect where two divs are stacked on top of each other, and the content of the lower div is only revealed in a certain area around the cursor. Is it possible to make o ...

Struggling to get your HTML to Express app Ajax post request up and running?

I’m currently in the process of creating a Node Express application designed for storing recipes. Through a ‘new recipe’ HTML form, users have the ability to input as many ingredients as necessary. These ingredients are then dynamically displayed usi ...

Having trouble uploading images from my personal computer onto Phaser 3

Currently in the process of coding a game for a school project using Phaser. I am quite new to Phaser and have very little knowledge of JavaScript. Despite searching online for potential solutions, none seem to be effective for me. I have included my cod ...