0

So I am trying to convert an array of strings to an array of numbers using the following code.

let a = ["0", "0"];
let b = Array.from(a, parseInt);
console.log(b);

and what I get is

b = [0, NaN];

I am familiar with a similar issue using Array.map() since it provides three arguments to parseInt() and the second argument (index) is interpreted as a radix by parseInt(). But it shouldn't be the case for Array.from().

Can someone give me an explanation please?

shrys
  • 5,860
  • 2
  • 21
  • 36
Jiří Lechner
  • 750
  • 6
  • 19
  • 1
    it is just the same approach of `map` with the second parameter of `Array.from`. – Nina Scholz Jul 02 '19 at 09:01
  • This happens because the callback function (in thi case, parseInt) is invoked with two arguments, which are the current value and the index of the value in the original array. Considering what said, parseInt is invoked with two arguments and, in parseInt, the second argument is the radix: https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/parseInt hence the callback in the second item is invoked with value `'0'` and radix `1`, yielding `NaN` – briosheje Jul 02 '19 at 09:05
  • Ok, the MDN documentation doesn't specify the callback signature. But that it is the same as using `map()` is mentioned later in the text. – Jiří Lechner Jul 02 '19 at 09:09
  • Change this `Array.from(a, parseInt);` for this `Array.from(a, ([n]) => parseInt(n));` this way, you're avoiding the problem with the implicit param `radix` you're passing through the index from function `Array.from(...)` – Ele Jul 02 '19 at 09:11

1 Answers1

-2

You need to have the actual function, not a reference:

let a = ["0", "0"];
let b = Array.from(a, e => parseInt(e));

console.log(b);

The issue is that using map (which is what the second argument of Array.from is) passes three arguments to the callback - the current item (what you want), the index (unnecessary), and the array (unnecessary). All three of these get applied to parseInt - so it looks like this:

let b = Array.from(a, (item, index, arr) => parseInt(item, index, arr));

Unfortunately, parseInt uses the second argument as the base of the number it produces (as in, decimal is base 10, binary is base 2, octal is base 8, hexadecimal is base 16). And the second argument passed is the index. So it's attempting to parse 0 to a number in base 1, which doesn't exist.

You could also just use the Number constructor.

let a = ["0", "0"];
let b = Array.from(a, Number);

console.log(b);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79