Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda