educative.io

Educative

Using filter() instead of map()

The link to the page is: https://www.educative.io/courses/the-complete-javascript-course-build-a-real-world-app-from-scratch/qVlyoEpxYEk

The final line of the solution is:
const result = filter(filter(students,femaleList),avgGrade);

I understand this part: filter(students,femaleList).
But why are we applying filter() again with avgGrade? Isn’t filter() supposed to only return array items that meet the given criteria given in the function? Here we’re trying to apply avgGrade to all students; why are we using filter() instead of map(), and why does using filter(students,femaleList).map(avgGrade) not work?

Hi @Amy_Li,

This part filter(students,femaleList) extracts the female entries from the students results. It will return the [Anna, f, 4.5,3.5,4][Martha, f, 5,4,2.5,3]. But we also need the average grade of the females. So inner filter is used to extract the female entries and an outer filter is used to get the average grade of the selected females from the student results.

Map function returned the whole array and the filter returned only those values that passed the test. Filters test every element of an array against a provided function. Only elements that pass this test are added to the returned array.

We need the average grades of only females from the array instead of all students in our case.