Please help me to understand how does this code work

Hello everyone. I’ve recently started doing some katas from codewars. I solved this kata, however wasn’t able to understand fully how it works. Could you please explain me code execution? I’ve tried some code visualizers, but still don’t have any clear understanding. Thanks in advance for your time and help. Here is the link to kata Training on Isograms | Codewars
Below is the code:

let abc = 'isIsogram';
function isIsogram(str) {
  let arr = str.toLowerCase().split('').sort();
  console.log(arr);
  for (let i = 0; i < arr.length - 1; i++) {
    if (arr[i] === arr[i + 1]) {
      return false;
    }
  }
  return true;
}
console.log(isIsogram(abc));

function isIsogram(str) {
  return !/(\w).*\1/i.test(str);
}
console.log(isIsogram(abc));

Could you write which part is confusing you? Do you have any suspicions how/why that works?

1 Like

Hello @sanity! Thanks a lot for your time and help. I don’t understand clearly a part about loop and if statement. Don’t know exactly, how it loops and why there’s “arr.length - 1” - this confuses me a lot)
I think that part where it says if (arr[i] === arr[i + 1]) here it compares in the first iteration index 0 and 1 if they are equal, it’ll return false, if not it’ll return true. This part somehow I got it, but loop part confuses me.

@tori-pak hello, I know about that index in JS starts at 0. Why do we need in a function to write arr.length - 1, if we could just simply do i < arr.length here we also have stopping condition, it’s a length of the array. So, this part is still unclear for me. Thanks for your time and help!

Hey, np!

In this particular loop, since every iteration is comparing current ‘i’ with the next one, ‘i + 1’, we need to stop the loop at ‘arr.length - 1’ index so the code in ‘if’ statement can run.

Otherwise if we use ‘i < arr.length’, the ‘arr[i + 1]’ code will throw an error, since it’s going to be undefined.

2 Likes

@tori-pak thanks a lot, for what does ‘np’ word stand for?)

Nugget Party :smiley:

haha well, it’s short for ‘no problem’ :slight_smile:
By the way, I’ve deleted previous post as it was not relevant to the solution

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.