JavaScript map() method

Today yet another great array method, following reduce() and filter(), there is map().

What does map especially do well? It returns an array of specific values, let's say you only want a list of prices from your products?

Or a combined full name based on two fields?

Let me show you how map makes our lives easier for that.

Using the Javascript map() method

Let's start by creating an array of items.

const items = [
  { name: 'T-shirt plain', price: 9 },
  { name: 'T-shirt print', price: 20 },
  { name: 'Jeans', price: 30 },
  { name: 'Cap', price: 5 }

Now next we just want the prices really.

We could loop the items and push the price to a new array right?

let prices = [];
items.forEach(item => {
// [ 9, 20, 30, 5 ]

Success! But we needed to define an empty array and manually loop, it can just be made easier.

const prices = => {
  return item.price;
// [ 9, 20, 30, 5 ]

Ah cool! Same, but better.

As mentioned you can also use it to combine things let's say we have a list of users.

const users = [
  { firstname: 'Louise', lastname: 'Belcher' },
  { firstname: 'Bob', lastname: 'Belcher' },
  { firstname: 'Tina', lastname: 'Belcher' },
  { firstname: 'Jimmy', lastname: 'Pesto' }

Now we want to get the full names:

const fullnames = => {
  return `${item.firstname} ${item.lastname}`;
// [ 'Louise Belcher', 'Bob Belcher', 'Tina Belcher', 'Jimmy Pesto' ]

I hope you learned what cool things the map() method can bring, and give you an understanding of how to use it.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Apurv Chimralwar's photo

Randomly searched for javascript map, wasn't expecting to get clarified within a minute. Thanks, and keep writing it helps....

Chris Bongers's photo

Wow Apurv, thanks that is wonderful, glad you found it useful and it helped you 🤟

Rutik Wankhade's photo

I am grateful for having people like you in the community Chris Bongers. Learning a lot with daily-dev-tips.

Chris Bongers's photo

Thank you so much Rutik, so glad you're learning from these!