Summary - Array transformations
Compute a class grade average with map, filter and reduce.
Summary - Array transformations
In this group you met the four core tools of array transformation: map transforms, filter selects, find grabs the first match, and reduce folds to a single value. some and every answer with a boolean.
You can also chain them: filter first, then map, then reduce. This flow is perfect for computing a class grade average. The original array always stays safe.
Exercise Compute the class average
Find the average of the grades array: first sum with reduce, then divide by the length. Store the result as average and print it.
Show example solution
const grades = [60, 75, 90, 50];
// compute the average
const average = grades.reduce((acc, grade) => acc + grade, 0) / grades.length;
console.log(average);
Exercise List the names of passing students
From the students array, filter those whose grade is 50 or higher, then take each one's name property into passingNames. Print the result.
Show example solution
const students = [{name: "Ed", grade: 40}, {name: "Ada", grade: 75}, {name: "Bob", grade: 90}];
// names of passing students
const passingNames = students.filter(s => s.grade >= 50).map(s => s.name);
console.log(passingNames);
Test yourself
-
Match each method to its job
- map
- transforms every element
- filter
- keeps matching elements
- find
- returns first match
- reduce
- folds to one value
-
sum passing grades by chaining
const grades = [40, 65, 80, 30]; const passingSum = grades.filter(g => g >= 50).reduce((acc, g) => ____, 0); console.log(passingSum);Show answer
const grades = [40, 65, 80, 30]; const passingSum = grades.filter(g => g >= 50).reduce((acc, g) => acc + g, 0); console.log(passingSum);