How to list an Array with . map()?

Asked

Viewed 387 times

1

How can I list an Array using . map()? in the example below, I was able to list using a for loop, how can I get the same result using a . map()?

var students = [
    {
        name: 'Anna',
        grade: 6
    },
    {
        name: 'John',
        grade: 4
    },
    {
        name: 'Maria',
        grade: 9
    }
];
for(var i = 0; i < students.length; i++){
    console.log(students[i].name);
    console.log(students[i].grade);
}

1 answer

3


Just to go through all and show, is usually used the foreach.

In the case of map it could be used, however it is usually used to create a new array resulting from the change of the array in question.

In the case of forEach and of map, it is called with a function, the first parameter being the "pointer", or current value, the second parameter is the index of the array in question (optional parameter), and the third parameter (also optional) is the array itself, so it can be:

students.map(function (student, index, arr) {
  console.log(student.name);
  console.log(student.grade);
  console.log(index);
  console.log(arr);
});

students.forEach(function (student, index, arr) {
  console.log(student.name);
  console.log(student.grade);
  console.log(index);
  console.log(arr);
});

In ES6 mode, in which case it is not necessary the optional parameters, only to list the data would be like this, with forEach and map:

var students = [
    {
        name: 'Anna',
        grade: 6
    },
    {
        name: 'John',
        grade: 4
    },
    {
        name: 'Maria',
        grade: 9
    }
];
// for(var i = 0; i < students.length; i++){
//    console.log(students[i].name);
//    console.log(students[i].grade);
//}
students.forEach(student => {
  console.log(student.name);
  console.log(student.grade);
});
students.map(student => {
  console.log(student.name);
  console.log(student.grade);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.