4

Someone pointed this weird array result in JavaScript and I was hoping someone could explain why this happens.

If I have an array like so:

var arr = ["10", "10", "10", "10"];

And I try to map those "10"'s to integers like so:

arr.map(parseInt);

The result will be an array with the values: [10, NaN, 2, 3] (I ran all of this code in Chrome's console)

I expected the result to be: [10, 10, 10, 10]

I understand that JavaScript can parse integers from string into different numbering systems, like binary, which I think explains where the 2 and 3 three are coming from, kind of. But why would parseInt change to parsing them in different bases? Could someone please explain why this is the result I get?

1
  • In other words, parseint("10", 0) = 10, parseint("10", 1) = NaN , parseint("10", 2) = 2 , parseint("10", 3) = 3 It was a simple misunderstanding of the functions. Commented Jun 1, 2016 at 16:55

4 Answers 4

4

Array.prototype.map accepts a callback which takes 3 arguments:

  1. The current element
  2. The index of the element
  3. The array that this function was called on

parseInt takes up to two arguments:

  1. The string to parse
  2. (Optional) The radix i.e. the base of the number.

So in passing parseInt to map, you essentially get the following calls:

parseInt(arr[0], 0); // if 0, same as default
parseInt(arr[1], 1); // Parse as base 1
parseInt(arr[2], 2); // Parse as base 2 or binary
parseInt(arr[3], 3); // Parse as base 3

An easier and more effective way of accomplishing what you're trying is to use Number:

var arr = ["10", "10", "10", "10", "23", "74"];
console.log(arr.map(Number));

Sign up to request clarification or add additional context in comments.

Comments

1

Read the man page on parseInt, it takes two parameters. A value and a radix.

Array.prototype.map sends three parameters: currentValue, index, array

Use Number instead

["10", "20"].map(Number)

Comments

1

it works this way :

 var arr = ["10", "10", "10", "10"];
 var newArr = arr.map(function(num){
    return parseInt(num);
 });

 console.log(newArr);

Comments

0

You see that weird behaviour because the actual Parseint considers second value as radix

ParseInt syntax: parseInt(string, radix);

This behaviour is explained in developer.mozilla.org

For reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.