Home > database >  Check whether a string is an isogram with Javascript - logic review
Check whether a string is an isogram with Javascript - logic review

Time:11-11

My attempt to solve if a string is an isogram is below:
I can't work out why my code doesn't work. Please can someone help to explain why?
An isogram has no repeating letters consecutively or non-consecutively.
I have attempted to: 1- convert the string to lowercase and make it an array. 2- create an if check to return true if the string is empty. 3- run a for loop through the array and compare the firstIndex of and lastIndex of each letter. If the first instance and last instance are not the same, then the string cannot be an isogram and therefore return false.??

    function isIsogram(str){
      str = str.toLowerCase();
      let text = str.split("");
      if (text.length === 0) { 
        return true;
      }
      for (let i = 0; i < text.length; i  ) {
        if ( text.indexOf(text[i]) !== text.lastIndexOf(text[i]) ){
          return false;
        } else {
          return true;
        }
      } 
    }

CodePudding user response:

A simple change should resolve the issue. Your existing function only considers the first character. This will then skip any repeating characters further along in the string, for example it returns true for 'abb' which is incorrect of course.

It's best to continue to the end of the loop and only return true when we're sure there are no repeating characters.

function isIsogram(str){
    str = str.toLowerCase();
    let text = str.split("");
    if (text.length === 0) { 
        return true;
    }
    for (let i = 0; i < text.length; i  ) {
        if (text.indexOf(text[i]) !== text.lastIndexOf(text[i]) ){
            return false;
        }
    }
    return true;
}

const testInputs = ['abb','aab','aba','abc','abcdz'];
testInputs.forEach(input => console.log(`isIsogram(${input}): ${isIsogram(input)}`));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Here's another implementation, using a Set() to count unique characters. If the string has no repeating characters, then the number of unique characters given by the set size should be the same as the input string length.

function isIsogram(str){
    return new Set(str).size === str.length;
}

const testInputs = ['abb','aab','aba','abc', 'abcdz'];
testInputs.forEach(input => console.log(`isIsogram(${input}): ${isIsogram(input)}`));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related