Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Index last vowels 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 and 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]}`)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading