0

I was solving basic algorithm problems, and I got stuck in this code.

The problem was to get string data and remove duplicated charactors. For instance, input: 'ksekkset', output: 'kset'

And this is my solution.

function solution(s) {
  let answer = "";
  for(let i in s) {
    if(s.indexOf(s[i]) == i) answer+=s[i];
  }
  return answer;
}

My question is, why do I get correct answer only when I put '==' inside if()? When I put '===' why if() only returns false?

If I use for loop, '===' also works..

function solution2(s) {
  let answer = "";
  for(let i=0; i<s.length; i++) {
    if(s.indexOf(s[i])===i) answer+=s[i];
  }
  return answer;
}

I'm so confused!

siennaY
  • 23
  • 2

1 Answers1

1

As @VLAZ mentioned above.. the == vs === isn't the only difference.

I wrote changed around your program to try all combinations of the for/in change and === change, and you can see that the only one that doesn't work as expected is === with for/in.

Strange that for a string, for/in gives you the indices as strings even though they are the numbers!

const s = "stackoverflow"; // repeated 'o' makes answer interesting

const answers = {
  answerForInTripple: "",
  answerForInDouble: "",
  answerForTripple: "",
  answerForDouble: "",
};

for(let i in s) {
  if(s.indexOf(s[i]) == i) {
    answers.answerForInDouble += s[i];
  }
  if(s.indexOf(s[i]) === i) {
    answers.answerForInTripple += s[i];
  }
}

for(let i=0; i < s.length; i++) {
  if(s.indexOf(s[i]) == i) {
    answers.answerForDouble += s[i];
  }
  if(s.indexOf(s[i]) === i) {
    answers.answerForTripple += s[i];
  }
}

console.log(answers);
console.log('here is the difference between what you are comparing');
for(let i in s) {
  const idx = s.indexOf(s[i]);
  console.log(typeof i, i, typeof idx, idx);
}

console.log('simpler example');

for (let i in 'test') console.log(typeof i, i);
Alex028502
  • 3,486
  • 2
  • 23
  • 50