Palindrome Finding Methods
Question is to finding the palindrome words in the array
let arr = ["Mango", "Orange", "Banana", "Pineapple", "Noon", "Day", "Night", "Morning"];
Feel free to use dev tools console tab after seeing the methods you can find the palindrome words there
Palindrome word is identified in methods, Noon
Method 1
Using for loop only to findout
for (let i = 0; i < arr.length; i++) {
let singleWord = arr[i];
let reversedWord = "";
for (let j = 0; j < singleWord.length; j++) {
reversedWord = singleWord[j].toLocaleLowerCase() + reversedWord;
}
if (reversedWord === singleWord.toLocaleLowerCase()) {
console.log('Palindrome word is identified in method 1,' + singleWord);
}
}
Method 2
Using string methods to split, reverse and join the words
for (let i = 0; i < arr.length; i++) {
let singleWord = arr[i];
let reversedWord = singleWord.toLocaleLowerCase().split("").reverse().join().replaceAll(',', '');
if (reversedWord === singleWord.toLocaleLowerCase()) {
console.log('Palindrome word is identified in method 2,' + singleWord);
}
}
Method 3
Using while loop with a condition and using for...of loop for char in string
let i = 0;
while (i < arr.length) {
let singleWord = arr[i];
let reversedWord = "";
for (let char of singleWord) {
reversedWord = char.toLocaleLowerCase() + reversedWord;
}
if (reversedWord === singleWord.toLocaleLowerCase()) {
console.log('Palindrome word is identified in method 3,' + singleWord);
}
i++;
}