Filtering array to contain palindrome elements in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of String / Number literals and returns a subarray of all the elements that were palindrome in the original array.

For example

If the input array is −

const arr = ['carecar', 1344, 12321, 'did', 'cannot'];

Then the output should be −

const output = [12321, 'did'];

We will create a helper function that takes in a number or a string and checks if its a boolean or not.

Then we will loop over the array, filter the palindrome elements and return the filtered array.

Therefore, let’s write the code for this function −

Example

The code for this will be −

const arr = ['carecar', 1344, 12321, 'did', 'cannot'];
const isPalindrome = el => {
   const str = String(el);
   let i = 0;
   let j = str.length - 1;
   while(i < j) {
      if(str[i] === str[j]) {
         i++;
         j--;
      } else {
         return false;
      }
   }
   return true;
};
const findPalindrome = arr => {
   return arr.filter(el => isPalindrome(el));
};
console.log(findPalindrome(arr));

Output

The output in the console will be −

[ 12321, 'did' ]
raja
Published on 21-Oct-2020 15:21:30
Advertisements