'Need to use a function inside the map of a list
I'm just learning JavaScript and I'm trying to do the following. Let's say I have the following function:
f(a,b) {return(a+b)}
And now I have a list of for example the following:
list = [1,2,3]
What I would like to do is map for that list in which I call the function above f with a predefined value and each value of the list. I've tried this:
listB = list.map(x => f(x+23))
But it returns a NaN, and if I add some brackets that snippet returns undefined.
What's going on and how can I solve it?
Solution 1:[1]
you have error in your function call f(x + 23). This is because your function f expects 2 arguments, and you forward only one. number + undefined -> NaN
Solution 2:[2]
you can re-write it as
const list = [1, 2, 3, 4];
const listb = list.map(f);
function f(num) {
return num + 23;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stefan Zivkovic |
| Solution 2 | Shiju |
