lundi 10 mai 2021

Need help understanding why this works

This function checks if a word is an isogram, meaning that there are no duplicate letters (not case sensitive). I understand why I have to change it to lowercase and iterate through the string, but I got confused on this part: "if(splitt.indexOf(splitt[i]) !== i)". Why do I have to check the index of? Maybe, I am confused on what this line of code is trying to say. Can someone help explain this line of code. Thank you!

function isIsogram(str) {
  //turn input string into all lowercase
   //console.log(str.toLowerCase());
  var lower = str.toLowerCase();
  // split lowercase string
    //console.log(lower.split(''));

  var splitt = lower.split('');

  //iterate through split string [A, l, g, o, r, i, s, m]
  for(var i = 0; i < splitt.length; i++){
   // console.log(splitt.indexOf(splitt[i]) !== i);

if(splitt.indexOf(splitt[i]) !== i){
  return false;
  }
 }
 return true;
// if we have encountered current element within srting again
  //return false
//otherwise
  //return true



}


var output = isIsogram("AlgoriSsm");
console.log('should be false:', output);

Aucun commentaire:

Enregistrer un commentaire