How do we locate the Last Word in a Statement dynamically?

A simple but interesting one! -How do I find the last word in a phrase or sentence?

A few days ago my mentor sent me this funny & interesting youtube shorts and tasked me to find the pattern in the content & code it.

I tried to solve this in a simple & efficient way. Here's my code snippet for the same.

function patternIdentify(phrase) {
    let patternArr = phrase.split(' ');
    let index = patternArr.length-1;
    console.log(patternArr[index]);
    // return patternArr[index];
}
patternIdentify("What is your name"); //name
patternIdentify("Are you having a good time tonight");//tonight
patternIdentify("Do you want to go back to them or you want to stay with Trump");//Trump
  • Firstly, I am taking a sentence/phrase as input and splitting into an array of words using split() method with space as delimiter.

  • In the next step, checking the length of the splitted array & subtracting it with 1 because we need to locate the last element/word in the array as we don't know the last index of an array but we do know that last index of an array is surely array.length-1, in our case it is (patternArr.length-1).

  • In the final step I am able to return/print the last word of the statment.

Being a competitive person I took up the task & am sharing the experience having solved it. Hope, this was a simple & fun yet interesting one. Keep an eye out for more such creative & engaging logics/algorithms.