Tell us what’s happening:
I am trying to solve the palindrome checker with just a for loop; I have not yet completed all the Functional Programming Challenges, but I would like to try with what I have covered so far and later revisit this challenge and redo it with higher-order functions.
My plan is the following:
- convert str to lowercase and then to an array with split(), and save the new array to a variable arr;
- create a new, empty array newArr to store alpha-numeric characters from arr;
- iterate over each element of arr and if it is alpha-numeric, push it to newArr;
- reverse newArr with a reverse for loop and push() and compare it with newArr;
Right now I am stuck at 3. The test does not seem to be working and after the loop newArr is just [] [] []
. But why?
Your code so far
function palindrome(str) {
let arr = str.toLowerCase().split(""); // convert str to lowercase and to an array
let newArr = []; // create an empty array to store filtered alphanumerical characters
let test = /\w/; // set up test for alphanumeric characters
// test whether each character in the array is an alphanumerical character
for (let i = 0; i < arr.length; i++) {
if (arr[i] === test) {
// if it is, push it to the newArr
newArr.push(arr[i]);
}
// newArr logs [] [] [] - why?
console.log(newArr);
}
return true;
}
palindrome("eye");
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36
.
Challenge: Palindrome Checker
Link to the challenge: