Checking an array for palindromes - JavaScript  



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 it’s a boolean or not. Then we will loop over the array, filter the palindrome elements and return the filtered array

Example

Following is the code −

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

This will produce the following output in console −

[ 12321, 'did' ]
Updated on: 2020-09-18T13:15:59+05:30

978 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements