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