Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

172
Visualizações
how to find duplicate in string and return index js

need to return index of second occurrence if no duplicate return not found

const forAll = (str) => {
  var forAllmini;
  for (var i = 0; i < str.length; i++) {
    forAllmini = (str[i] != str[i+1]) ? 'not found': `@ index ${i}`;
  }
  return forAllmini
}

console.log(forAll('carrot'))

i tried this but i only get 'not found'

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

If you need to find repeated chars you can use a set and check it like this:

const forAll = (str) => {
  const visited = new Set();
  for (var i = 0; i < str.length; i++) {
    if(visited.has(str[i])) return `@ index ${i}`;
    visited.add(str[i]);
  }
  return 'not found'
}

console.log(forAll('carrot'))

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to break your for like this:

const forAll = (str) => {
  var forAllmini;
  for (var i = 0; i < str.length; i++) {
    forAllmini = (str[i] != str[i+1]) ? 'not found': `@ index ${i}`;
    if (forAllmini != 'not found') {
      break;
    }
  }
  return forAllmini
}

console.log(forAll('carrot'))

about 4 years ago · Juan Pablo Isaza Relatório

0

Because the forAllmini is overwritten:

const forAll = (str) => {
  for (var i = 0; i < str.length; i++) {
    if(str[i] == str[i+1]) return `@ index ${i}`;
  }
  return 'not found';
}

console.log(forAll('carrot'))

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda