Check for Palindromes - .reverse() on array not working

Check for Palindromes - .reverse() on array not working
0

#1

Using the Chrome Dev Tools to view the console, my array, ‘reverseStr’ doesn’t seem to be '.reverse()'ing properly, or the order of the array does not change and I can’t figure out why. I’ve tried different means of initializing they array to start, in case some how the datatype was wrong, but with no luck.

Further, if the string portion of the console output is omitted, one can definitely see they are data of ‘array’ type. Any thoughts as to why this is not working ?

Your code so far

function palindrome(str) {
  // Good luck!
  lowerCaseStr = str.toLowerCase();
  lowerCaseStr = lowerCaseStr.replace(/\W/gi,'').replace(/_/g,'');
  var originalStr = lowerCaseStr.split('');
  var reverseStr = originalStr.reverse();

 console.log("Org Str" + originalStr);
 console.log("Rev Str" + reverseStr);
 
}
palindrome("eye");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36.

Link to the challenge:


#2

The reverse() method actually reverses the array in place, so both originalStr and reverseStr are reversed.
Array.prototype.reverse()

See it here.


#3

Thanks Ariel,

I see this better now. Using .slice(0), rather than the assignment operator to copy data, not just the pointer.

Thanks.


#4

When you use the reverse function on an array, it reverses “in-place”, so the originalStr array is reversed and then you assign a reference of the reversed array to reverseStr. They will look the same. You can join reverseStr back to make a string and then compare it to lowerCaseStr though.