Home > database >  how to find duplicate in string and return index js
how to find duplicate in string and return index js

Time:08-18

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'

CodePudding user response:

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'))

CodePudding user response:

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'))

CodePudding user response:

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'))

CodePudding user response:

You were mutating the variable in every iteration, and not breaking out when duplicate was found.

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'))

CodePudding user response:

Loop through the string one char at a time, starting from index 1. You don't need to save intermediate results, just return from a loop to break out of it.

The problem with your forAllmini variable is that it is overridden on each loop iteration.

function forAll(input) {
  for (let i = 1; i < input.length; i  = 1) { // start at index 1, not 0!
    if (input[i - 1] === input[i]) { // check if previous char === current char
      return `@ index ${i - 1}`; // return index of first doubled character
    }
  }
  return 'not found';
}



console.log(forAll('carrot'));
console.log(forAll('none'));

  • Related