DEV Community

Cover image for Using map() in Javascript
Guilherme Toti
Guilherme Toti

Posted on

Using map() in Javascript

Hello guys, how’re you doing?

Hope you’re doing great!

In this post, I want to talk about the map() function, a function related to Arrays in Javascript that I use a lot and it’s very useful for various situations.

I’ll show you guys some real-life examples, hope you guys like it!

map()

The map() function is very useful when you need to translate or change the elements in an Array.

It loops through the Array from left to right, creating a new Array, and, for each item, it runs some function that you passed as args, and your function must return a value, so, this return will be the new item of the new Array.

Let’s see an example below.

Imagine that you receive this data from your API:

const data = [
  {
    id: 1,
    name: 'John Doe',
    location: {
      city: 'São Paulo',
      state: 'SP',
      country: 'Brazil',
      zipcode: '00000-000'
    }
  },
  {
    id: 2,
    name: 'Don Juan',
    location: {
      city: 'Rio de Janeiro',
      state: 'RJ',
      country: 'Brazil',
      zipcode: '11111-111'
    }
  },
  {
    id: 3,
    name: 'The Rock',
    location: {
      city: 'Curitiba',
      state: 'SP',
      country: 'Brazil',
      zipcode: '22222-222'
    }
  }
]
Enter fullscreen mode Exit fullscreen mode

So, you have an array of objects with:

- user id
- name
- location
  - city
  - state
  - country
  - zipcode
Enter fullscreen mode Exit fullscreen mode

Let’s figure out we don’t need all this data, we need only an array with objects like:

{
  id: 1,
  name: 'John Doe',
  city: 'São Paulo'
}
Enter fullscreen mode Exit fullscreen mode

Problably, to resolve that, you may be thinking in something like:

let newData = []

for (var index in data) {
  const user = data[index];

  newData.push({
    id: user.id,
    name: user.name,
    city: user.location.city
  });
}
Enter fullscreen mode Exit fullscreen mode

Right?

It isn’t wrong, and it’s works, but, there is a lot of steps, and, we can do it better!

Doing that way, you are:

  1. Instancing a new variable;
  2. Doing a for loop through the data Array, getting each index;
  3. Using this index to access the current element of the Array;
  4. Pushing the new object to the variable previously created;

The map() function provides an easy way to do exactly this and with less steps!

Check below how to write the same using map():

const newData = data.map(user => ({
  id: user.id,
  name: user.name,
  city: user.location.city
}));
Enter fullscreen mode Exit fullscreen mode

Maybe your reaction be like:

wtf

But, keep calm, i’ll explain every step!

When you execute Array.map(), to clear your mind in a real-life example, you can think in something like:

- The map() gets your Array;
- Loop through it, and, for each item it:
  - Execute the function you’ve passed, passing the current item as an argument;
  - Update the current item value, to the returned value from your function;
Enter fullscreen mode Exit fullscreen mode

So, this also can be re-written to something like:

function parseUser(user) {
  return {
    id: user.id,
    name: user.name,
    city: user.location.city
  }
}

const newData = data.map(parseUser);
Enter fullscreen mode Exit fullscreen mode

It will produce the same result and has the same effect.

And if you’re familiar with ES6, you can re-write it to:

const newData = data.map(({ id, name, location: { city }}) => ({ id, name, city }));
Enter fullscreen mode Exit fullscreen mode

But i’ll not talk about ES6 now, maybe in another post! :P

Using any of the examples above, if you run a console.log(newData), you will receive:

[    
  {
    id: 1,
    name: 'John Doe',
    city: 'São Paulo'
  },
  {
    id: 2,
    name: 'Don Juan',
    city: 'Rio de Janeiro'
  },
  {
    id: 3,
    name: 'The Rock',
    city: 'Curitiba'
  },
]
Enter fullscreen mode Exit fullscreen mode

So, that’s it guys, as expected!

I hope you guys understand about the map() function, but, if you have any questions please feel free to contact me!

That's all folks!

I hope you guys enjoy it, and keep learning!

Top comments (4)

Collapse
 
chukwuebukakennedy profile image
Kennedy

Hey! I like your humor..nice example.

Collapse
 
guilhermetoti profile image
Guilherme Toti

Thanks man!
Well, I try to give information and teach using humor because, at least to me, it looks way easier to understand!

Collapse
 
zolotarev profile image
Andrew Zolotarev • Edited

In first example you are using ingoing param "item", but in the function's body used variable "user".
Is it right?

Collapse
 
guilhermetoti profile image
Guilherme Toti

Nope, this is not right. It was my mistake, I will fix that, thanks for let me know!