map()
Description
map()
is used to perform the same action on each individual value in a list.
That way, it lets you transform a list of values into another list, which comes in especially handy when working with user-provided values like nationalities
or sources_of_income
.
Also see MAP for a non-method version.
Example: Double some numbers
SUM(
[1, 2, 3].map(number => number * 2)
)
We call map on a list, here the list of numbers
[1, 2, 3]
.The argument within map is the function we use on each element, here
number * 2
. It takes each number from that array and multiplies it by 2. With each calculation, the variablenumber
is replaced by the next value from the list, until the last value has been dealt with. We chose the name to benumber
as the variable before=>
. We could have also chosenn
orx
if we would have wanted to.Since a SUM operator encloses the MAP function, the final output will be the added total of all doubled values - in this case: 12.
The calculations step-by-step:
1 * 2 = 2
2 * 2 = 4
3 * 2 = 6
The intermediate result of MAP is the new list [2, 4, 6]
SUM adds these new values: 2 + 4 + 6 = 12.
Last updated
Was this helpful?