Bendegúz Hajnal

web development blog

Map function

2020-02-25 Bendegúz HajnalFP

The map function

In its essence it’s a higher order function which accepts an array and a function. It applies this transformation to every element of the array. Let’s look at the definition of map in Haskell language.

map :: (a -> b) -> [a] -> [b]
-- type declaration: it accepts a function
-- and an array, and returns another array

map _ []     = []
-- Haskell uses pattern matching, map will
-- return [] when the 2nd param is the empty array

map f (x:xs) = f x : map f xs
-- This definition will apply in every other case:
-- We apply the f on the first element of the list,
-- and we concat the result with
-- the remaining transformed values, recursively.

Now let’s use it.

arr = [5,4,12,1]
transformedArr = map (+2) arr -- [7,6,14,3]

We just created a new array, where we incremented all elements by 2. The type of elements in the resulting array do not necessarily have to be of the same type. For example, we could use a function which transforms numbers to strings:

arr = [0,2,4,6]

-- another example of pattern matching below
toString :: Int -> String
toString 1 = "One"
toString 2 = "Two"
toString 3 = "Three"
toString 5 = "Five"
toString 7 = "Seven"

nextNumToString :: Int -> String
nextNumToString num = toString (num + 1)

transformedArr = map nextNumToString arr
-- ["One","Three","Five","Seven"]

On the web

ECMA-262 specification’s 5th edition (the last before ES6 or ECMAScript 2015) introduced Array.prototype.map function(, ES6 gave arrow functions, learn more about them here).

let new_array = arr.map(element =>  element + 2)
// This does the same thing as the first example in Haskell

I prefer defining small functions as arrow functions for readability, but you can use the syntax including the function keyword in almost every case.

Where are they used

In React (and most modern UI frameworks), this is the method you would use to render the same component multiple times after each other.

function NumberList({ numbers }) {
  return (
    <ul>
      {numbers.map(number => (
        <Number
          value={number}
          key={number.toString()}
          /* A key prop in this case is needed,
          so React knows which element to update in the list */
        />
      ))}
    </ul>
  );
}

Another example would be populating a <select /> tags options. You would have to map the array of possible values to an array of objects with ‘label’ and ‘value’ properties.

Closing off

I’ll write about the other widely used array methods too in the future. Until then, you can find a good reference for them here, here is the wikipedia article for map, and if you are interested in functional programming and/or Haskell, I recommend reading this book.

  • © Bendegúz Hajnal 2020