The palindrome checking function is malfunctioning and needs to be fixed

I have attempted to create a function to determine if a number is a palindrome, but it seems to be malfunctioning. The concept is simple - splitting the number into two halves, comparing them, and reversing one half to check for symmetry.

function palindromeChecker(number) {
  let numArray  = String(number).split('');
  let firstHalf = numArray.slice(0, numArray.length / 2);
  let secondHalf = numArray.slice(numArray.length / 2, numArray.length);
  if (secondHalf.length > firstHalf.length) {
    secondHalf.shift();
  }
  console.log(firstHalf)
  console.log(secondHalf.reverse())
  return firstHalf == secondHalf.reverse();
}

console.log(palindromeChecker(1234321));

Although I was optimistic about the outcome, viewing both arrays and the final boolean result displayed:

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

If anyone can shed light on this issue, I would greatly appreciate it. Thank you!

Answer №1

According to the JavaScript documentation, the .reverse() method reverses the array in-place.

For example, when you use array2.reverse(), you are essentially reversing the actual second half of the array as well (resulting in [1,2,3]).

Subsequently, when you compare the two halves with the statement:

array1 == array2.reverse();

You are actually comparing [1,2,3] with [3,2,1]. Therefore, only reverse it once to prevent this discrepancy.

Additionally

Understanding array equality in JavaScript can be tricky, as shown in this Stack Overflow thread.

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

You may consider using:

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

or

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

Answer №2

array1 and array2.reverse() have values that are not based on their content, but rather on their system address.

To transform your array into a string:

function luckyNumber(value)
  {
  let 
    arr  = [...value.toString(10)]
  , str1 = arr.slice(0, arr.length / 2).join('')
  , str2 = arr.slice(arr.length / 2, arr.length).reverse().join('')
    ;
  if (str2.length > str1.length) 
    str2 = str2.slice(0,-1); 

  console.log( str1 , str2 )

  return str1 === str2;
  }

  console.log(luckyNumber(1234321));

Answer №3

Comparing arrays requires a specific approach, try this method instead:

return JSON.stringify(array1) === JSON.stringify(array2);

I once encountered a similar situation and adapted the solution to fit your requirements:

function checkPalindrome(value) {
let stringValue = String(value);

  let sizeOfString = stringValue.length;
  
  for(let i = 0; i < sizeOfString / 2; i++){
      if(stringValue[i] !== stringValue[sizeOfString - 1 - i]){
          return false;
      }
  }
  return true;
}

console.log(checkPalindrome(1234321));
console.log(checkPalindrome(1234320));
console.log(checkPalindrome(1234311));
console.log(checkPalindrome(12344321));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leverage the power of ssh2-promise in NodeJS to run Linux commands on a remote server

When attempting to run the command yum install <package_name> on a remote Linux server using the ssh2-promise package, I encountered an issue where I couldn't retrieve the response from the command for further processing and validation. I' ...

Ways to retrieve the data from promises after they have been resolved?

I'm struggling to retrieve the values from getPeople(0,4). function getPeople(start, end) { const peopleArray = []; for (let i = start; i <= end; i++) { peopleArray.push( axios.get(`https://www.testsite.net/api/test/workers/ ...

Click on a specific button within a DataTable row

I am working with a dataTable that fetches data from the database using Jquery. In each row, there are two buttons for accepting or rejecting something. My goal is to make the accept button disappear when rejecting and vice versa. public function displayT ...

I attempted to set up a Discord bot using JavaScript on Replit, but unfortunately, it seems to only respond when I mention the bot specifically, rather than to any regular

I've successfully created a python discord bot, but I'm encountering issues with the javascript one. Despite trying various solutions from StackOverflow, I'm unable to understand how to get it working. The plethora of online solutions for d ...

Issue with module exports not being defined in IE11/Edge

I am experiencing difficulties with an npm module that was updated to ES2015. My application is built in ES2015, bundled by browserify, and compiled with babelify. I am currently trying to upgrade a npm module called credit-card for validation, which has ...

Express/NodeJS encountering a CORS problem, causing services to be inaccessible in Internet Explorer

Currently, I am working on a REST-based service implemented in Express/NodeJS. The code includes CORS (Cross Origin Resource Sharing) implementation to allow services to be consumed from browsers like Chrome and Firefox. However, there seems to be an issue ...

Creating intricate structures using TypeScript recursively

When working with Angular and TypeScript, we have the power of generics and Compile-goodness to ensure type-safety. However, when using services like HTTP-Service, we only receive parsed JSON instead of specific objects. Below are some generic methods that ...

Adjust the background color of the table header in Google Charts

Is it possible to dynamically change the background color of the header row (and rows) in Google Charts based on values from a PHP database? The documentation suggests using the following code: dataTable.setCell(22, 2, 15, 'Fifteen', {style: &a ...

Experimenting with code within a window event listener function

I have a component in my AngularJS application that is functioning correctly. However, when it comes to test coverage, everything after the 'window.addEventListener('message',' part is not being covered. Should I create a mock object f ...

Unable to transfer information from the Parent component to the Child component

Can you help me solve this strange issue? I am experiencing a problem where I am passing data from a parent component to a child component using a service method that returns data as Observable<DemoModel>. The issue is that when the child component ...

Angular Array -- combining numerous data points within a single entity

I'm attempting to build an AngularJS array and apply a filtering function based on the object's name. The challenge I'm facing is trying to filter the array using multiple values within one object name, as shown below. Desired solution: { ...

Eliminate any rows in the array that are blank

I needed a way to remove empty rows from an array in php. After using array_filter, I achieved the desired result. Below is the code I implemented: $cars = array ( array("Volvo",22,18), array("BMW",15,13), array("Saab",5,2), array("",'&apos ...

Prisma unexpectedly updates the main SQL Server database instead of the specified database in the connection string

I have recently transitioned from using SQLite to SQL Server in the t3 stack with Prisma. Despite having my models defined and setting up the database connection string, I am encountering an issue when trying to run migrations. Upon running the commands: ...

Is it possible for a nonce to be utilized for multiple scripts, or is it restricted to

Exploring the Origins About a year ago, our company embarked on a journey to implement CSP throughout all our digital platforms. Each of these platforms was built using an express.js + react framework. In order to adhere to the guideline that "Each HTTP r ...

What is causing the ESLint error when trying to use an async function that returns a Promise?

In my Next.js application, I have defined an async function with Promise return and used it as an event handler for an HTML anchor element. However, when I try to run my code, ESLint throws the following error: "Promise-returning function provided t ...

Discovering the stable order indices of the top n elements within an array

I am working with a number and an array: n = 4 a = [0, 1, 2, 3, 3, 4] My goal is to identify the indices that correspond to the top n elements in array a, but I want them in reverse based on their size. In case of equal element sizes, I prefer a stable o ...

Having trouble with AJAX within AJAX not functioning properly?

Similar to the Facebook commenting system, I am aiming for comments to be appended to previous ones and displayed all at once. However, currently the comments only show up after the page is reloaded. Please Note: Each post initially loads with just two co ...

Error message: "Uncaught ReferenceError: $ is not defined in BackboneJS and RequireJS"

In my Backbone application, I am using RequireJS. However, I keep encountering the error message Uncaught ReferenceError: $ is not defined, indicating that my libraries may not be loading properly. This is what my RequireJS config looks like: require.con ...

Ensuring Form Validity with jQuery for Exclusive Radio Buttons

How can I display an error message when a radio button value is not equal to a specific value? I have a series of yes/no questions and want to show disclaimers under each set of buttons if the value provided is null or different from what is required. Most ...

Ensuring precise accuracy in JavaScript; transforming 0.5 into 0.5000

My current challenge involves converting every fraction number to n decimal places in JavaScript/Node.js. However, I've encountered a roadblock as it appears impossible to convert 0.5 to 0.5000. This discrepancy is causing my test cases that anticipat ...