DEV Community

David Bell
David Bell

Posted on • Originally published at davidbell.space

A Quick Look at the map() Method in JavaScript

The map() array method in JavaScript manipulates an array and returns a new array with the altered data.

Example 1

Let's say we have an array of objects called dogs

const dogs = [
  {
    name: "Scruffy",
    breed: "Labrador",
    age: 3,
    likes: ["being a good boi", "walks"],
  },
  {
    name: "Shandy",
    breed: "Bulldog",
    likes: ["sticks", "treats"],
  },
]
Enter fullscreen mode Exit fullscreen mode

Let's say we want a new array from dogs showing just the dog breeds available.

const breeds = dogs.map(dog => dog.breed)
// [ 'Labrador', 'Bulldog' ]
Enter fullscreen mode Exit fullscreen mode

We map over dogs and for each dogs available we add the breed to our new array.

Example 2

In this example we want to return a new array of objects, of each dogs name and what the dogs likes.

const nameAndLikes = dogs.map(dog => {
  return {
    name: dog.name,
    likes: dog.likes,
  }
})
/*[ 
    { 
    name: 'Scruffy', 
    likes: [ 'being a good boi', 'walks' ] 
    },
    { name: 'Shandy',
     likes: [ 'sticks', 'treats' ] 
     }
  ] */
Enter fullscreen mode Exit fullscreen mode

This time we set the keys we want and then set the values to dog.name and dog.likes. Remember this returns a new array and doesn't alter the original.

Let's connect

Twitter

Top comments (1)

Collapse
 
fetchworkglenn profile image
Glenn • Edited

Additional things to look at for beginners:

filter()
reduce()

Object:
Set()