How does the map function work?

2

I am studying JavaScript , learning the functions map() , filter() and reduce() , and found a

asked by anonymous 14.09.2017 / 09:40

1 answer

3

Map

The function map maps the elements of an array for a new array with the result of a function.

Taking the example of the documentation we can consider an array of numbers and use map to get double each of the numbers as follows:

var numeros = [1, 5, 10, 15];
var dobros = numeros.map(function(x) {
   return x * 2;
}); //[2, 10, 20, 30]

We see that the function for each element of the array numeros is called, thus constructing a new element for the array dobros . This element is always the parameter of the function used, which in the example above was x .

Problem in your code

The problem is that the byName function expects to receive an object that has the name property and that in its example does not have:

console.log(byName(students));

Because an array, the students , is passed instead of an array object. To pass a specific student could do so:

console.log(byName(students[0]));

That would be getting the name of the first student.

Example:

const students = [
    { name: 'Anna', grade: 6 },
    { name: 'John', grade: 4 },
    { name: 'Maria', grade: 9 }
];

var byName = function(object) {
    return object.name
};
console.log(byName(students[0]));

However, the purpose of this exercise was not this, as it is mentioned in the article you mentioned, but instead map the original list to a list of names through the function map and byName doing:

students.map(byName);

Example:

const students = [
    { name: 'Anna', grade: 6 },
    { name: 'John', grade: 4 },
    { name: 'Maria', grade: 9 }
];

var byName = function(object) {
    return object.name
};

console.log(students.map(byName));

You could even create a second function for this whole list mapping:

var byNames = function(list) {
    return list.map(byName);
};

And then use it appropriately:

byNames(students); // ["Anna", "John", "Maria"]

Map with Arrow functions

Another yet simplified way using ES6's Arrow Functions :

students.map(x => x.name);

What would make it not even necessary to have the function byName

Applying the same to the initial example of doubles, this could then be rewritten like this:

var numeros = [1, 5, 10, 15];
var dobros = numeros.map(x => x * 2); // [2, 10, 20, 30]

Example working with byName :

const students = [
    { name: 'Anna', grade: 6 },
    { name: 'John', grade: 4 },
    { name: 'Maria', grade: 9 }
];

//byName agora com arrow function
console.log(students.map(x => x.name));
    
14.09.2017 / 11:30