Filtering array to contain palindrome elements in 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 palindrome or not. Then we will loop over the array, filter the palindrome elements and return the filtered array.

Understanding Palindromes

A palindrome is a word, phrase, or sequence that reads the same backward as forward. For example, "did", "12321", and "racecar" are palindromes.

Solution Approach

We'll use two functions:

  • isPalindrome() - Helper function to check if an element is a palindrome
  • findPalindrome() - Main function that filters the array

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' ]

How It Works

The isPalindrome function converts the element to a string and uses two pointers approach:

  • Start from both ends of the string
  • Compare characters moving inward
  • If any pair doesn't match, return false
  • If all pairs match, return true

The findPalindrome function uses Array.filter() to create a new array containing only palindrome elements.

Alternative Using Reverse Method

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

const isPalindromeReverse = el => {
    const str = String(el);
    return str === str.split('').reverse().join('');
};

const findPalindromeAlt = arr => {
    return arr.filter(el => isPalindromeReverse(el));
};

console.log(findPalindromeAlt(arr));
[ 12321, 'did' ]

Conclusion

Both approaches effectively filter palindromes from mixed arrays. The two-pointer method is more memory efficient, while the reverse method is more concise and readable for simple cases.

Updated on: 2026-03-15T23:19:00+05:30

365 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements