Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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' ]
Advertisements