paint-brush
Using JavaScript’s map functionby@daveford
70,060 reads
70,060 reads

Using JavaScript’s map function

by David FordApril 22nd, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

The map function simply transforms one array into another array. For example, suppose you have an array of person objects but what you really need is an array of names (strings):
featured image - Using JavaScript’s map function
David Ford HackerNoon profile picture

The map function simply transforms one array into another array. For example, suppose you have an array of person objects but what you really need is an array of names (strings):

The map function will convert the array of person objects into an array of names (strings).

Lets say this is the array you start with:






const friends = [{id:1, name: 'Dave',age:50},{id:2,name: 'Kellie',age:42},{id:3,name: 'Max',age:12},{id:2,name: 'Jack',age:12}];

and you want to convert it to this:

['Dave', 'Kellie', 'Max','Jack']

You start by defining a mapping function. The mapping function operates on a single row, converting (or mapping) one person into one name (string):

const mappingFunction = p => p.name;

Then you pass the mapping function to array.map like this:

const names = friends.map(mappingFunction);

which returns:

['Dave', 'Kellie', 'Max','Jack']

You can also do this as a one liner:

const names = friends.map(p => p.name);

Map function in React JSX

This type of thing is very common in React JSX. To map an array of person objects to an array of <li> elements, use a mapping function like this:

const mappingFunction = p => <li>{p.name}</li>;

To ensure React’s DOM diff’ing works correctly, you’ll need to provide each <li> with a unique key:

const mappingFunction = p => <li key={p.id}>{p.name}</li>;

In context, this might look something like this:





render(){return <ul>{friends.map(p => <li key={p.id}>{p.name}</li>)}</ul>;}