user2824374
user2824374

Reputation: 220

How to find indices without using indexOf or other built in functions?

I have a situation where I need to find the index of the target string. My code works for single character, but not for characters more than 1. Any idea how can I approach this?

const findAllIndices =  (stringToCheck, target) => {
let index=[];
  for (let i = 0; i < stringToCheck.length;i++) {
    if (stringToCheck[i] === target) {
      index.push(i);
    }
  }
console.log(index)
}

findAllIndices('the dog jumps over the river', 'the')
findAllIndices('the dog jumps over the river', 'o')

Upvotes: 0

Views: 511

Answers (2)

Layhout
Layhout

Reputation: 1580

here is my try, this is a fun challenge

const findAllIndices = (stringToCheck, target) => {
    let index = [];
    for (let i = 0; i < stringToCheck.length; i++) {
        let subStringToCheck = "";
        if (stringToCheck[i] === target[0]) {
            for (let j = 0; j < target.length; j++) {
                subStringToCheck += stringToCheck[i + j];
            }
            if (subStringToCheck === target) index.push(i);
        }
    }
    return index;
}

console.log(findAllIndices('the dog jumps over the river', 'the'));
console.log(findAllIndices('the dog jumps over the river', 'o'));

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370679

If you can't use any built-in functions, you'll have to build up the substring at the i index from the number of characters in target, then check if the substring matches the target.

const findAllIndices = (stringToCheck, target) => {
  const matchingIndicies = [];
  for (let i = 0; i < stringToCheck.length; i++) {
    let substring = '';
    for (let j = 0; j < target.length; j++) {
      substring += stringToCheck[i + j];
    }
    if (substring === target && substring.length === target.length) {
      matchingIndicies.push(i);
    }
  }
  console.log(matchingIndicies)
}

findAllIndices('the dog jumps over the river', 'the')
findAllIndices('the dog jumps over the river', 'o')

Upvotes: 1

Related Questions