Find the First Palindromic String in an Array in js

105 views Asked by At

Here I have written a program that will find the first palindromic string in an array, like if the array is ["abs", "car", "ada", "racecar", "cool"], and I want output like "ada" so I have written a program that represents the palindromic logic representation, so here the output is not coming as expected. Can you please rectify and modify that program?

function isPalindrome(str) {
let left=0,right=str.length
while(left<right){
    if(str.charAt(left)!=str.charAt(right)){
        return false
    }
    left++;
    right--;
}
return true
}
function firstPalindrome(words) {
  for (let i=0;i<words.length;i++) {
    if (isPalindrome(words[i])) {
      return words[i];
    }
  }
  return "";
}

console.log(firstPalindrome(["abc", "car", "ada", "racecar", "cool"]));
1

There are 1 answers

2
Daniel Beck On

Here's a much simpler approach:

function isPalindrome(str) {
  // compare str with its reverse:
  return str == str.split('').reverse().join('')
}

function firstPalindrome(words) {
  // filter the array to just palindromes, then return the first one (if any)
  return words.find(isPalindrome)
}

console.log(firstPalindrome(["abc", "car", "ada", "racecar", "cool"]));