Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function to check number is palindrome not working correctly

I’ve created this function to check whether a number is palindrome or not, but it’s not working. It’s pretty simple in fact, it will have to arrays which are the two halves of the number, the first one and the second one (reversed) and it will compare them.

function luckyNumber(value) {
  let array  = String(value).split('');
  let array1 = array.slice(0, array.length / 2);
  let array2 = array.slice(array.length / 2, array.length);
  if (array2.length > array1.length) {
    array2.shift();
  }
  console.log(array1)
  console.log(array2.reverse())
  return array1 == array2.reverse();
}

console.log(luckyNumber(1234321));

I thought it was going to work alright, but when I printed both arrays and the final boolean in the end, it threw this:

[ '1', '2', '3' ]
[ '1', '2', '3' ]
false

Can someone explain this to me? Thank you!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Per the JS Docs, .reverse() happens in-place.

i.e. – when calling .reverse() the array is reversed in memory.
So, when logging the output of array2.reverse(), you’re also (accidentally) reversing the actual 2nd half of the array. (so it becoms [1,2,3]).

Then, when comparing the two halves, you’re reversing it again

array1 == array2.reverse();

And if fact you’re comparing [1,2,3] with [3,2,1].

So, reverse it only once.

ALSO

Array equality is hard in js

[1,2,3]==[1,2,3] // false

You could opt for:

JSON.stringify(arr1) === JSON.stringify(arr2);

or

const isEqual = arr1.length === arr2.length && arr1.every((value, index) => value === arr2[index]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading