Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript 1.6 Array.map() and Array.filter() not working with built in functions as arguments

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?

like image 925
bucabay Avatar asked Apr 15 '10 18:04

bucabay


People also ask

Can I use map and filter together JavaScript?

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.

What is filter () map () and reduce ()?

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.

What is the difference between array map and filter in JavaScript?

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.

How do you use map and reduce together?

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.


1 Answers

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) })
like image 78
bobince Avatar answered Sep 23 '22 00:09

bobince