OiO.lk Blog javascript TypeError: string is not a function when Array.findIdex is used
javascript

TypeError: string is not a function when Array.findIdex is used


Not sure if I’m doing an error in the code, but when I try to find the index of the letter z that is in the array I’ve split I will get this error:

TypeError: string "z" is not a function
    at Array.findIndex (<anonymous>)

Here is the code:

const chars: string = "abcdefghilmnopqrstuwxyz0123456789@-_+*(),.#";
let outputMatrix: Array<string> = [];
let outputWord: string = "";

// Split input matrix function 
const splitMatrix = async (inputMatrix: string) => {
  let splitted = inputMatrix.split(''); 
  let uppercaseChars = splitted.findIndex('z');
  console.log(uppercaseChars)
  console.log(splitted)
  return splitted;
}

// Generating random word
const createRandomString = (splittedChars: Array<string>, length?: number) => {
  const defaultLength: number = 12;
  const min: number  = 0;
  const max: number = splittedChars.length;
  let num: number;

  if (length) {
    for(let i: number = 0; i < length; i++) {
      num = Math.floor(Math.random() * (max - min) + min);
      outputWord += splittedChars[num];
    }
    return outputWord;
  } else {
    for(let i: number = 0; i < defaultLength; i++) {
      num = Math.floor(Math.random() * (max - min) + min);
      outputWord += splittedChars[num];
    }
  }
  console.log('Generated password', outputWord);
}

const main = () => {
  splitMatrix(chars)
    .then( (outputMatrix) => {
      createRandomString(outputMatrix);
    });
}

main();

What I want to do is to get the index of the z letter and after this extract all the elements that are before the letter including the letter to uppercase them.



You need to sign in to view this answers

Exit mobile version