javascriptindexing

Index of last vowel in a string


I've been sent a project in which I'm to index the last occurrence of a vowel within a string. I've unfortunately been receiving inconsistent results, ranging from -1 which it naturally wouldn't be, to 84, or 50. I've attempted running this as a loop, but unfortunately I'm not quite able to grasp any alternate way to solve this nor am I able to fully understand why my results are inconsistent.

I've attempted the following:

let myString = 'jrfndklhgfndjkjlkgperfijfhdknsadcvjhiiohjfkledsopiuhgtyujwsdxcvhgfdjhiopiwquhejkdsoiufghedjwsh'
let substr =  ('a','e','i','o','u');
const lastVowel = myString.lastIndexOf(substr);

console.log(lastVowel);

I'm not necessarily asking for any answers, an explanation, or even hinting at a solution would be appreciated. If any any were to be pasted, however, I'd be happy tinkering with it to further comprehension. I'm not really going to turn any form of help away.


Solution

  • Since there is no findLastIndex() method yet, what you can do, is reverse your array, get the first index of a vowel and subtract that from the string's (length-1) to get your initial position:

    let myString = 'jrfndklhgfndjkjlkgperfijfhdknsadcvjhiiohjfkledsopiuhgtyujwsdxcvhgfdjhiopiwquhejkdsoiufghedjwsh'
    let vowels =  ['a','e','i','o','u'];
    
    let arr = myString.split("").reverse(); // split string into array, and reverse it
    let indexOfLastVowelInReverse = arr.findIndex(e => vowels.includes(e))
    
    if(indexOfLastVowelInReverse != -1) { // if the index is -1 there is no vowel in the string
      let index = myString.length-1-indexOfLastVowelInReverse
      console.log(`Last vowel found at index ${index}: ${myString[index]}`)
    }