0

This is the problem I'm trying to solve:

Write a Javascript code that checks whether a passed string is palindrome or not? Note: A palindrome is a word or phrase that reads the same backward as forward; eg. madam,racecar, etc.

And this is my code for it.. I'm not sure why it's not working. Can anyone assist?

function is_Palindrome (str){
  
   array1 = str.split('')
  array1_orig = array1.map(a => a)
  array2 = array1.reverse()
  console.log(array1_orig)
 console.log(array2)
  
  

  for (let i = 0; i <array1.length; i++){
    if(array1[i] === array2[i]){
      console.log("a match") 
    }
    else{
      console.log("not a match")
    }
  }


 

}


is_Palindrome("desk")

is_Palindrome("desk")

desk is obviously NOT a palindrome, so it should return "not a match" but the code isn't doing that

2 Answers2

1

In the line array1.reverse(), reverse will mutate the array1 object itself. This is cause of your issue.

Actually, you may not need to reverse call itself. You can just traverse the elements only till mid point and compare the ith element from start and end.

function is_Palindrome(str) {
  array1 = str.split("");

  const len = array1.length;
  let isMatch = true;

  for (let i = 0; i < len / 2; i++) {
    if (array1[i] !== array1[len - 1 - i]) {
      isMatch = false;
    }
  }
  return isMatch;
}

console.log("desk - ",is_Palindrome("desk"));
console.log("racecar - ", is_Palindrome("racecar"));
Siva K V
  • 10,561
  • 2
  • 16
  • 29
0

When calling myArray.reverse(), myArray gets reversed too.

I fixed the problem by using array1_orig instead :

function is_Palindrome (str){
  
   array1 = str.split('')
  array1_orig = array1.map(a => a)

  // Here, you are reversing array1 and storing the result in BOTH array1 and array2.
  array2 = array1.reverse()
  console.log(array1_orig)
 console.log(array2)
  
  

  for (let i = 0; i <array1_orig.length; i++){
    // Change both the line ABOVE and the line BELOW
    if(array1_orig[i] === array2[i]){
      console.log("a match") 
    }
    else{
      console.log("not a match")
    }
  }


 

}

console.log("Testing : DESK")
is_Palindrome("desk")
console.log("Testing : RACECAR")
is_Palindrome("racecar")
Invizio
  • 382
  • 1
  • 8