subLength() problem, why doesnt my code work?

You must select a tag to post in this category. Please find the tag relating to the section of the course you are on E.g. loops, learn-compatibility
Hey, I don’t understand why my code does not work. The push method just adds the same index to the array twice.
// Write function below

function subLength (long, short) {
  let counter = 0;
  let longSplit = long.split('');
  let indizes = [];
  for (charac of longSplit) {
    if (charac === short) {
      counter += 1;
      indizes.push(longSplit.indexOf(charac));
    }
  }Preformatted text
  if (counter < 2 || counter > 2) {
    return 0;
  };
  let dif = indizes[1] - indizes[0];
  return dif;
}
subLength('mraian', 'a');

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile:

Hi @byte5582530562
from the MDN docs:

The indexOf() method returns the first index at which a given element can be found in the array…

In your case, a for loop or forEach (with the index as a parameter) would be a better option.