Looking for a way to determine in JavaScript whether the last item in an array is a number or not? Keep in mind that the last element could be either a number or a string, depending

console.log("case 1")
var event = "Year 2021";
console.log(typeof(parseInt(event.split(" ").pop())) === "number");
console.log("case 2")
var event = "Year mukesh";
console.log(typeof(parseInt(event.split(" ").pop())) === "number");
console.log("case 3")
var event = "Year mukesh";
console.log(typeof(event.split(" ").pop()) === "number");
console.log("case 4")
var event = "Year 2021";
console.log(typeof(event.split(" ").pop()) === "number");

case 1 demonstrates that using parseInt on a proper number at the end of a string gives us a true value, which is valid.

In case 2, when there's a non-numeric string at the end and we use parseInt, it surprisingly returns a valid number type, resulting in a false outcome.

Case 3 showcases that without parseInt, a string at the end correctly gives us a false result.

Case 4 shows that even with a number at the end, not using parseInt still yields a false result because the number is within quotation marks, making it a string.

Now, the challenge is determining whether the last element in an array is a string or an integer since user input could be any mix of strings and numbers such as "Hello darkness" or "Hello 221".

For more clarification, check out this jsFiddle link.

Answer №1

Check if a value is NaN by using the isNaN method:

console.log("scenario 1")
var item = "Month May";
console.log('Is it numeric?', !isNaN(item.split(" ").pop()));

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

Nodemailer is failing to send emails on Heroku

Recently, I encountered an issue that has been puzzling me. I use cloud9 for work and nodemailer works perfectly fine, sending all emails from a form I created. However, when I deployed a small server to Heroku with just a change in an environmental vari ...

reconfigure form credentials with JavaScript

I am currently working on a form that includes a textbox and a button for submitting data using ajax. <input type="password" id="password" /> <button id="addaccount" onclick="showload();">Add</button> When the user clicks on the button, ...

Using cascading style sheets to switch a page into editing mode

Is it possible to change the view of a page after clicking a button without using javascript, and instead relying solely on CSS? I want to display a page with information where users can click an edit button and make changes within the same view rather th ...

SPRING --- Tips for sending an array of objects to a controller in Java framework

Can someone help me with this issue? I am using AngularJS to submit data to my Spring controller: @RequestParam(value = "hashtag[]") hashtag[] o The above code works for array parameters but not for an array object. This is my JavaScript script: $http ...

Getting the correct JSON field value from a JavaScript Promise object in the right way

Trying to fetch data in JSON format from a URL, I encountered an issue where the value of responseData.title differed between two calls made within the second .then() function below: var getTitleForId = async function(id) { if (!id) return fal ...

Challenges encountered while using Selenium WebDriver to upload images

I'm having trouble adding an image as a normal attachment to an email (not as an inline image). When inspecting the HTML DOM with Firebug, I noticed there are two elements with xpath //input@type='file', which is due to the presence of two b ...

Encountered an issue while building npm: "Error: Unable to locate module @restart/context

Lately, I've encountered an issue with npm build after upgrading to the latest version of react-bootstrap (1.0.0-beta.6). While creating an optimized production build... Failed to compile. Module not found: '@restart/context/forwardRef'. P ...

When using jQuery to select elements of a specific class, make sure to exclude the element that triggered the

A dynamic number of divs are generated from a data source. Each div contains an image button and another div with text. While the actual scenario is more complex, we can present a simplified version: <div id="main"> <div id="content_block_1" ...

Loading event in HTML5 video element is in progress

I'm interested in creating a loading animation for an html5 video, similar to the display on Youtube videos (reference: https://www.youtube.com/watch?v=5vcCBHVyG50) I attempted using the canplay event but I believe I may have misunderstood its true p ...

Simpler and more sustainable methods for embedding HTML elements using a configuration file

Currently, I am devoting my time to a toy project that heavily relies on JavaScript. A key component of this project is a JSON file that contains configurations and input descriptions, along with range values and options. This JSON file enables me to easil ...

retrieve a static method that returns an asynchronous value

Is there a way to have a static ES6 method in my code that simply returns a value instead of a promise? I'm looking for a solution to this problem: export default class Member { static existingMember() { var _existingMember; // DB.findExist ...

Exploring Typescript within React: Creating a property on the current instance

Within my non-TypeScript React component, I previously implemented: componentWillMount() { this.delayedSearch = _.debounce((val) => { this.onQuerySearch(val); }, 1000); } This was for debouncing user input on an input field. The corres ...

Even when there is a change in value within the beforeEach hook, the original value remains unchanged and is used for dynamic tests

My current project setup: I am currently conducting dynamic tests on cypress where I receive a list of names from environment variables. The number of tests I run depends on the number of names in this list. What I aim to achieve: My main goal is to manip ...

Next.js is unable to identify custom npm package

My unique custom package structure looks like this: package.json Posts.js Inside Posts.js, I have the following code: const Posts = () => { return <div>List of posts</div> } export default Posts; After publishing to the GitHub Package ...

Artwork expanding incorrectly on HTML canvas

I'm encountering an issue while attempting to draw on an HTML canvas. I've specified 50 circles and multiple lines within a canvas of size 1000x1000 px, but not all circles are appearing as expected. My assumption is that the elements are being ...

Guidelines for choosing a single integer from a collection of integers and floating-point numbers that have been extracted from a string

In my code, I have a set of doubles and ints that I parsed named gradeList. This data will be passed to a constructor. The grade list looks like this: "5 - 90 85 95.5 77.5 88" The '5' is an integer but the rest should be double values. My parsing ...

Leveraging Arrays with AJAX Promises

I am currently working on making multiple AJAX calls using promises. I want to combine the two responses, analyze them collectively, and then generate a final response. Here is my current approach: var responseData = []; for (var i=0; i<letsSayTwo; i++ ...

What is the best way to create space or add margins to a set of curved stacked images?

Below is the code I am currently using to arrange curved images side by side: <a-curvedimage v-for="(value, index) in model" :theta-start="setThumbThetaStart(thumb, index)" :theta-length="30"> // The thumb variable is not being utilized, only ...

Is there a way to make a try-catch block pause and wait for a response before moving

I've been successfully retrieving data from my Firestore database, but I've encountered a major issue that I can't seem to resolve... Whenever I click the "Read Data" button, I have to press it twice in order to see the console log of the d ...

PHP and JavaScript both offer methods for escaping variables that are written in the syntax ${HOST}

How can I safely handle variables from the database like ${HOST}? This issue arises when code is posted within <pre><code> tags. If left as it is, an error occurs: Uncaught ReferenceError: HOST is not defined. In this specific context, usin ...