Functional Programming - Use the map Method to Extract Data from an Array

Hi all, thanks for taking the time to look at my question :slight_smile:

I’m having a bit of trouble understanding this function in the example, so i understand that the map function will iterate over users to extract the results i want.

But what i dont understand is (user => user.name), why dont we have just name? How would i read the contents inside the brackets (user => user.name),

const users = [
  { name: 'John', age: 34 },
  { name: 'Amy', age: 20 },
  { name: 'camperCat', age: 10 }
];

const names = users.map(user => user.name);
console.log(names);

The console would display the value [ 'John', 'Amy', 'camperCat' ]

Thanks

map passes each element of the array to the callback function and then uses result from that function.

user => user.name is a function written using arrow syntax. It takes single argument named user, and returns user.name.

Without arrow syntax it could look like this:

const names  = users.map(function (user) {
  return user.name;
});

It could use just name when destructuring, but I’m not sure if that’s what you meant.

const names = users.map(({ name }) => name);
const names  = users.map(function ({ name }) {
  return name;
});

Just to add to these good responses… the user variable is defined by the function. It could be any vaiable name you like. User is referencing the current elemant of the array and passing it to the function

This code generates an array of objects called users, each of which has two properties: a name and an age.
Finally, a new array called names is created by using the map() method to extract only the name field from each object in the users array. The callback function that is passed as a parameter to the map() method is called once for each user in the users array.
In this instance, the callback function extracts and returns the name property from each object in the users array using an arrow function.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.