0

Using lodash in chrome (latest as of today).

_.map("0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0".split(":"), parseInt);

i get:

[0, NaN, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Seems like a basic operation.

duraid
  • 614
  • 7
  • 16
  • 3
    Possible duplicate of [javascript - Array#map and parseInt](http://stackoverflow.com/questions/262427/javascript-arraymap-and-parseint) – Ori Drori Nov 11 '16 at 20:51

2 Answers2

4

If you're already using Lodash, it's normally safer to replace native methods with Lodash ones when they exist.

In this case, I would use _.parseInt instead of just parseInt, as the latter may create unexpected results (as is the case here).

The following works as expected:

_.map("0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0".split(":"), _.parseInt);

If you're curious as to why the 'vanilla' parseInt method returns NaN, I believe that what is happening is the following:

  1. When you use _.map(collection, iteratee), the iteratee is actually called with three arguments: (item, index, collection). Source here.
  2. The problem here is that when you call JavaScript's native parseInt, the second argument is a radix that determines which base should be used to parse the integer (binary, octal, decimal, hexadecimal, etc.). Because the iteratee is called with three arguments, this messes up your radix and returns NaN. See here for MDN's explanation on how parseInt works.
  3. Lodash's _.parseInt() avoids that problem by adding a guard. It's usually safe to assume that Lodash protects its methods with guards like this to make sure you can use them as iteratees in other Lodash methods.
Fernando
  • 280
  • 2
  • 10
1

As I commented in this post, your problem can be solved without using lodash this way:

console.log(("0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0").split(":").map(Number));
Community
  • 1
  • 1
acontell
  • 6,792
  • 1
  • 19
  • 32