0

Part one of this code example is from MDN, and part two is from my imagination, apparently.

var array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

var array2 = ['1', '2', '3'];
var map2 = array2.map(parseInt);

console.log(map2); 
// expected output: [1, 2, 3]
// actual output: [1, NaN, NaN]

Can you explain why this output isn't mapping? parseInt is a function that takes a string and returns an integer. Each element in the mapped array is a number string, so each element in the output array should be a number, right?

Joshua M. Moore
  • 381
  • 6
  • 20
  • Regarding your edit; that is explained in the accepted answer on the duplicate question: `parseInt` takes two parameters, and the function provided to `map` is given three parameters. – Heretic Monkey Sep 15 '18 at 18:41

1 Answers1

0

Using array2.map(parseFloat) works because parseFloat do not expect a radix value as a second argument.

var array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

var array2 = ['1', '2', '3'];
var map2 = array2.map(parseFloat);

console.log(map2); 
// expected output: [1, 2, 3]
// actual output: [1, NaN, NaN]
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62