This works fine:
["655971", "2343", "343"].map(function(x) { return parseInt(x) }) // [655971, 2343, 343]
But this doesnt:
["655971", "2343", "343"].map(parseInt) // [655971, NaN, NaN]
The same happens for Array.filter()
What am I missing here?
JavaScript's Array#map() and Array#filter() functions are great when used together because they allow you to compose simple functions. For example, here's a basic use case for filter() : filtering out all numbers that are less than 100 from a numeric array. This function works fine on an array of numbers.
The functions map(), filter(), and reduce() all do the same thing: They each take a function and a list of elements, and then return the result of applying the function to each element in the list.
map creates a new array by transforming every element in an array individually. filter creates a new array by removing elements that don't belong. reduce , on the other hand, takes all of the elements in an array and reduces them into a single value. Just like map and filter , reduce is defined on Array.
Using reduce and map() together Here's how it's done: Map the array into an array of zeros and ones. Reduce the array of zeros and ones into the sum.
It's because map
passes more arguments than just the array item into the callback function. You get:
callback(item, index, array)
Normally your function would just ignore the arguments it didn't need. But parseInt
accepts an optional second parameter:
parseInt(string, base)
for the first call, base
is the index
0
. That works okay because ECMAScript defines that base=0
is the same as omitting the argument, and consequently allows decimal, octal or hex (using decimal in this case).
For the second and third items, base
is 1
or 2
. It tries to parse the number as base-1 (which doesn't exist) or base-2 (binary). Since the first number in the string is a digit that doesn't exist in those bases, you get a NaN
.
In general, parseInt
without a base is pretty questionable anyway, so you probably want:
["655971", "2343", "343"].map(function(x) { return parseInt(x, 10) })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With