Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
A palindrome is a word, number, or sequence that reads the same forward and backward. For example, "dad", "racecar", and 12321 are palindromes.
Problem Statement
If the input array is:
const arr = ['carecar', 1344, 12321, 'did', 'cannot'];
Then the output should be:
const output = [12321, 'did'];
Approach
We will create a helper function that takes in a number or a string and checks if it's a palindrome. Then we will loop over the array, filter the palindrome elements and return the filtered array.
Solution
const arr = ['carecar', 1344, 12321, 'did', 'cannot'];
const isPalindrome = el => {
const str = String(el);
let i = 0;
let j = str.length - 1;
while(i {
return arr.filter(el => isPalindrome(el));
};
console.log(findPalindrome(arr));
Output
[ 12321, 'did' ]
How It Works
The isPalindrome function converts any input to a string and uses two pointers (i and j) to compare characters from both ends moving toward the center. If all corresponding characters match, it returns true; otherwise false.
The findPalindrome function uses the filter method to create a new array containing only palindromic elements from the original array.
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 findPalindromeReverse = arr => {
return arr.filter(isPalindromeReverse);
};
console.log(findPalindromeReverse(arr));
Output
[ 12321, 'did' ]
Conclusion
Both approaches effectively identify palindromes in mixed arrays. The two-pointer method is more memory efficient, while the reverse method is more concise but creates additional string copies.
