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

Time:08-09

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

Have you considered String.prototype.matchAll()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll

let str = 'the dog jumps over the river'
console.log(Array.from(str.matchAll('the')).map(x => x.index))

Result: [ 0, 19 ]

  • Related