Why does this code work in finding the first non-duplicate letter in a string?

289 Views Asked by At

I'm doing some self practice with Javascript.

I'm working on a question that asks me to find the first letter in a string that does not have a duplicate.

After some playing around, I finally got it to work using indexOf and lastIndexOf. But even though I made a working solution, I just dont understand how my solution works.

It seems like if I grabbed two of the same letters it SHOULDN'T return the first non duplicate letter. but it does. In other words, I cant explain how the if statement is returning a non duplicate letter.

heres what I got:

function noRepeat(str) {
  strSplit = str.split("");

  for (let i = 0; i < strSplit.length; i++) {
    if (strSplit.indexOf(strSplit[i]) === strSplit.lastIndexOf(strSplit[i])) {
      return strSplit[i];
    }
  }
}
console.log(noRepeat("yoboTyoboznopno"));

0

There are 0 best solutions below