Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!