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!
3
Answers
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
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
You could opt for:
or
array1
orarray2.reverse()
values are not about content of them,but about their system address.
Change your array in string:
You cannot compare two arrays in that way, you can use this:
But i did something similar time ago, i modified to your needs: