1

What is the difference between map(func) and map(function(x) { return func(x); })?

Consider this example:

const lines = '1\n2\n3';
const result = lines.split('\n').map(parseInt);
console.log(result )

This returns [1, NaN, NaN] which is not what I expected. However:

const lines = '1\n2\n3';
const result = lines.split('\n').map(function(x){ return parseInt(x)});
console.log(result)

returns the expected: [1, 2, 3]. What is the difference between these two forms and why in the first example the result is not [1, 2, 3]?

Bo Vandersteene
  • 601
  • 7
  • 16
Mariy
  • 5,746
  • 4
  • 40
  • 57

3 Answers3

3

parseInt has a second parameter (radix).

Basically you perform this

value index parseInt comment
----- ----- -------- -----------------------------------------------------
  '1'     0        1 with radix 0, and value 1 parseInt assumes radix = 10
  '2'     1      NaN because of the wrong value for the radix
  '3'     2      NaN because of the wrong value for the radix

For converting to a number, you could use Number.

var lines = '1\n2\n3'

console.log(lines.split('\n').map(Number));

For getting integer values, you could use Math.floor as well.

var lines = '1\n2\n3'

console.log(lines.split('\n').map(Math.floor));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

The difference is that .map passes to its function 3 parameters:

.map(element, index, array)

when the parseInt function accepts 2 arguments

parseInt(string, radix)

So, you pass index as a radix. That is why your result is wrong. If parseInt was accepting just one argument it would work.

smnbbrv
  • 23,502
  • 9
  • 78
  • 109
2

Because the index from the map will be passed into the map function

let lines = '1\n2\n3'
let a = lines.split('\n').map(parseInt);
console.log(a)

// Your code above is expanded as below
a = lines.split('\n').map((x, i) => {
  return parseInt(x, i)
})

console.log(a)

// To fix it, use this
lines.split('\n').map(x => parseInt(x));
ne1410s
  • 6,864
  • 6
  • 55
  • 61
Tim
  • 3,755
  • 3
  • 36
  • 57