0

I've come across something a bit odd.

I'm trying to parse a string with a time in ( e.g. "12:00", "13:30") into two separate integers. I tried this:

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

But minutes comes out as NaN

I thought there was a problem with parseInt taking in "00", but when I tried parseInt("00") in the console I get 0.

Can someone shed some light on this?

renzyq19
  • 148
  • 1
  • 5
  • Because `parseInt()` takes an second (optional) argument, and Array#map provides a second argument to the passed function. You can use `.map(parseFloat)`, `.map(Number)`, `.map(Math.floor)` or `.map(int)` (something I usually have laying around `const int = v => 0|v, uint = v => v>>>0;` ) – Thomas Aug 12 '17 at 15:18

2 Answers2

2

Array#map calls the function with three arguments:

  1. The current element

  2. The current index

  3. The array

This means that in the following snippet, parseInt is called with "00" and 1 (which is the index):

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

The second argument to parseInt has to be greater than 2, otherwise NaN will be returned.

That's what happens here.

To solve that, you could use:

timeString = "12:00"
[hours, minutes] = timeString.split(":").map(v => parseInt(v, 10))
PeterMader
  • 6,987
  • 1
  • 21
  • 31
0

parseInt takes 2 arguments, parseInt(numberOrString, numberBase) which can be used for binary strings, hexadecimal strings etc. .map takes a callback with the first 2 arguments being .map(item, index). So basically you're calling parseInt("00", 1) which returns NaN.

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

Greg Hornby
  • 7,443
  • 1
  • 18
  • 17