Stuck - Check for Palindromes Challenge

/**pseudo code : challenge breakdown. get an input in a form of a string.

  1. normalize the input to ignore case
  2. normalize the input to ignore spacing
  3. Remove all non-alphanumeric characters (punctuation,spaces and symbols)
  4. Reverse the sting’s letters one by one or using some-sort of function that does it all at once
  5. create an if () that checks to compare the reverse string version with the original version that returns true for palindrome and false for not palindrome */

I know I did it in a very non efficient/elegant and didn’t use push()
i’m trying to find where is the logic error in my code?

when I comment out //str = strArr.join(); it returns false for all the string checkes

otherwise it returns true

Where is the logic mistake in my code?:fearful::smile_cat:


//My code

function palindrome(str) {
  
  str = str.toLowerCase();
  str = str.replace(/\s+/g,"");
  str = str.replace(/\W+/g,"");
  var strArr = str.split("");
  var reverseStrArr = strArr;
  
  
  for(var i = 0; i <= strArr.length - 1; i++) {
     
      reverseStrArr[i] = strArr[strArr.length - (i+1)];
    
  }
  var reverseStr = reverseStrArr.join();
   str = strArr.join();
  
  if(reverseStr == str){
    return true;
  }
  
  else {
    return false;
  }
}

palindrome("321");

Your code doesn’t replace lodash.
\W matches spaces as well.
var reverseStrArr = strArr; <- both variables point to the same object now.
Use debugger to find out what’s happening in your code.

Good luck

1 Like

Your for loop isn’t working as you intend I, try adding:

console.log(reverseStr); 
console.log(str);

after the variable assignments after the for loop to see what results you are getting, this will hopefully point you in the right direction

1 Like

when you do var reverseStrArr = strArr, you’re not duplicating strArr, reverseStrArr references that same array; That means if you modify the values of reverseStrArr, you’re modifying the array that strArr references as well.

Unlike primitive values (like strings, numbers or booleans), arrays and objects are not copied when assigned to a new variable.


// example 1
var a = 1;
var b = a;
b = 2;
console.log(a, b); // 1 2
// changing b doesn't change a

// example 2
var arr1 = [1,2,3];
var arr2 = arr1;

arr2.push(4);
console.log(arr1, arr2) // [1,2,3,4] [1,2,3,4]

arr1.push(5);
console.log(arr1, arr2); // [1,2,3,4,5] [1,2,3,4,5]

// arr1 and arr2 point to the same array
1 Like

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

1 Like