Using Array.prototype.map in conjunction with parseInt functions

Recently, I encountered something quite unusual.

I am attempting to separate a string containing a time (e.g. "12:00", "13:30") into two distinct integers. I experimented with the following approach:

timeString = "12:00"
[hours, minutes] = timeString.split(":").map(parseInt)

However, the output for minutes turns out to be NaN.

Initially, I suspected that parseInt was causing an issue when processing "00", but upon testing parseInt("00") in the console, it resulted in 0.

Could someone provide some clarification on this matter?

Answer №1

Array#map executes the function with three parameters:

  1. The current item

  2. The current position

  3. The array itself

In this code snippet, parseInt is invoked with "00" and 1 (which represents the index):

timeString = "12:00"
[hours, minutes] = timeString.split(":").map(parseInt)

The second argument for parseInt must be greater than 2 to prevent returning NaN.

This is the issue illustrated here.

To address this, you can use:

timeString = "12:00"
[hours, minutes] = timeString.split(":").map(v => parseInt(v, 10))

Answer №2

When using parseInt, make sure to provide two arguments: parseInt(value, base). This method can handle various number systems like binary and hexadecimal. Similarly, the .map function takes a callback with parameters .map(item, index).

To fix the issue of returning NaN when calling parseInt("00", 1), update your code as follows:


timeString = "12:00"
var [hours, minutes] = timeString.split(":").map(i => parseInt(i))

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

Inquiry on integrating Spotify with Axios for my debut solo project (beginner inquiry)

I have a question regarding my first solo project in React. I started learning code in September and I'm facing an issue while making a POST request to the Spotify API to retrieve an access token: Despite following the recommended 'Content-Type& ...

What is the most effective way to accurately identify the mobile platform of a user using JavaScript?

I need to determine whether a user has accessed the application through a browser on Android or iOS. The company would like to display slightly different content depending on the platform. While I am aware that navigator.platform can be used for this pur ...

Retrieve a boolean value through an Ajax call from a C# function using T4MVC

I have a search bar on my website with the following code: <form onsubmit="return IsValidCustomer()"> <input class=" sb-search-input" placeholder="Search for a customer..." type="text" value="" name="search" id="search"> <input cl ...

What is the best way to fetch and convert information from an API to display on a website?

I am encountering an issue while trying to retrieve data from an API. Below is my code with a fabricated access code. $(function () { var $data = ('#data'); $.ajax({ type: 'GET', url: 'http://api.openweathe ...

Issue with Typescript not recognizing default properties on components

Can someone help me troubleshoot the issue I'm encountering in this code snippet: export type PackageLanguage = "de" | "en"; export interface ICookieConsentProps { language?: PackageLanguage ; } function CookieConsent({ langua ...

unset() transforms an array into an object

After removing the first item from an array in PHP and converting it to JSON, I noticed that the result is read as an object instead of an array. Initially, the PHP array looks like this: $myArray = ["one", "two", "three", "four"] When sending this arra ...

Ensure that all necessary fields are filled out by applying 'required' validation to each one

In the form I'm working with, there are various input elements like text boxes, date pickers, and drop downs. My goal is to make all other fields required once a value is entered in any field. For example, if a value is entered in a text box, then all ...

managing browser pop-ups in selenium with the help of JavaScript

My objective is to input a username and password in the popup box that shows up every time the page loads. I am utilizing selenium for this purpose, and unfortunately, all attempts I've made so far have been unsuccessful. I attempted to use the follo ...

Navigating Angular: Discovering Route Challenges in Less Than an Hour

Can someone take a look at my code and help me out? I'm trying to learn Angular.js by following the popular Angular.js in 60 minutes video tutorial, but it seems like things have been updated since then. I'm having trouble getting my routes to wo ...

how to implement a delay in closing a window using JavaScript

I am currently developing a Google Chrome extension and I want to express my gratitude to everyone here for tolerating my sometimes silly questions. The functionality of the extension is quite basic but it works smoothly. However, I am facing an issue wher ...

What is the recommended approach for effectively cascading the deletion of a secondary object in MongoDB when an account is

My app allows users to create accounts and interact with posts by liking and sharing them. However, I'm facing an issue when a user decides to delete their account. I have managed to resolve most of the related data removal except for one specific cas ...

When retrieving keys and values from an associative array in PHP, it will not return all keys and values if they have the same key name

Currently, I am analyzing a file with the following data: Vélez Sarsfield|Zárate, Mauro|8|0|0|1|9 Estudiantes|Carrillo, Guido|5|1|0|2|8 Boca Juniors|Gigliotti, Emanuel|3|2|0|2|7 River Plate|Carbonero, Carlos Mario|4|2|0|0|6 Arsenal|Echeverría, Mariano|6 ...

SCRIPT1015: Unfinished string literal encountered while attempting to load string

Hi, I am facing an issue with the code in my ASP.NET Razor v2 cshtml file. I am trying to load a string into a paragraph from a C# list of strings. However, when the string being loaded contains certain characters, such as: + "<p>"+'Rejv&#2 ...

Create an interactive webpage that automatically generates new HTML elements after retrieving JSON data from a Web API during page load

I am currently in the process of developing a hybrid Android App using Phonegap/Apache Cordova. The main function of my app is to retrieve data from my web API, which is being served through JSON. I have implemented the following code snippet for this task ...

Checking the content of a textfield in React Material UI based on the user input

Hello! I am seeking a solution to trigger an error message whenever the value entered in the first text field is not equal to "28.71", otherwise display a correct message. Here is my current code: class Main extends React.PureComponent { render() { ...

How can I retrieve information from an HTML or JavaScript object?

Imagine a scenario where you have an HTML table consisting of 5,000 rows and 50 columns, all generated from a JavaScript object. Now, suppose you want to send 50 checked rows (checkbox) from the client to the server using HTTP in JSON format. The question ...

Confusion surrounding asynchronous functions in Node.js

When handling routes or endpoints with multiple operations, I often encounter scenarios where I need to perform additional actions. For instance, when deleting an item, it's necessary to also remove the related file from S3 along with deleting the col ...

What is the reason for the emergence of this error message: "TypeError: mkdirp is not recognized as a function"?

While running the code, I encountered an error indicating that the file creation process was not working. I am seeking assistance to resolve this issue. The code is designed to fetch data from the Naver Trend API and Naver Advertising API, calculate resul ...

The use of Handlebars expressions within the {{#each}} block is crucial

I am currently working on my new portfolio site and I have a question about how to place handlebars expressions inside an #each loop. The project is an express application generated by express-generator, and I am using the express-handlebars NPM package: ...

Using various conditions and operators to display or conceal HTML elements in React applications, particularly in NextJS

I am seeking ways to implement conditional logic in my React/Next.js web app to display different HTML elements. While I have managed to make it work with individual variable conditions, I am encountering difficulties when trying to show the same HTML if m ...