-1

I writing a method to find the longest palindrome in a sentence of words. So far I have used the for loop to do this but its not returning the correct word.

function findLongestPalindrome(sentence) {
  let wordArray = sentence.split(" ");
  let longestWord = 0;
  let word = " ";
  
  for(let i = 0; i < wordArray.length; i++) {
    if(longestWord < wordArray[i].length) {
      longestWord = wordArray[i].length;
      word = wordArray[i]
    }
  }
  return word;
}

Can anyone give me a tip on where I am going wrong?

andy86
  • 75
  • 1
  • 6
  • The problem is to find the longest palindrome not the longest word. A palindrome is a word that is the same when read backwards. – Talmacel Marian Silviu Nov 24 '20 at 10:17
  • Where are you checking if the word is a palindrome? This just gets you the biggest word. There are hundreds of examples online for checking if a word is a palindrome: [Palindrome check in Javascript](https://stackoverflow.com/questions/14813369) – adiga Nov 24 '20 at 10:18

1 Answers1

0

You are missing a function to check string is palindrome or not. Please refer the below code and you can further optimize using new Set() and refactoring the code.

function findLongestPalindrome(sentence) {
  let wordArray = sentence.match(/\b\w+\b/g),
      longestWord = 0,
      word = " ";

  for (let i = 0; i < wordArray.length; i++) {
    if (longestWord < wordArray[i].length && isPalindrome(wordArray[i])) {
      longestWord = wordArray[i].length;
      word = wordArray[i]
    }
  }
  
  return word;
}

function isPalindrome(str) {
  return str.split('').reverse().join('') === str;
}

console.log(
  findLongestPalindrome('This is an interesting sentence: kayak, november, anna')
)
adiga
  • 34,372
  • 9
  • 61
  • 83
Vishal Bartakke
  • 294
  • 1
  • 9
  • this doesn't return the longest single palindrome word. – andy86 Nov 24 '20 at 10:52
  • At least this is working for me. If you using any sentence which is not working send it with expected output, I can check – Vishal Bartakke Nov 26 '20 at 10:37
  • findLongestPalindrome('This is an interesting sentence: kayak, november, anna') // should return 'kayak' – andy86 Nov 27 '20 at 07:01
  • @andy86 if your sentence has separators other than a space `" "`, you can use [this regex](https://stackoverflow.com/a/36508315/3082296) which splits at [word boundaries](https://www.regular-expressions.info/wordboundaries.html). Please check the snippet in the answer. If it resolved your issue, please [mark it as accepted](https://meta.stackexchange.com/a/5235/289255) by clicking on the grey checkmark on the left. – adiga Nov 27 '20 at 07:53
  • [How do I create a runnable stack snippet?](https://meta.stackoverflow.com/questions/358992) – adiga Nov 27 '20 at 07:53