JavaScript map() method

JavaScript map() method

Chris Bongers
·Nov 22, 2020·

3 min read

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

Did you find this article valuable?

Support Chris Bongers by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
Share this