1 |
const numbers = [1,2,3]; |
Reduce sums up all the items in the array where the first parameter is the callback and second param is the starting value.
1 2 3 4 |
const result = numbers.reduce( (sum, item) => sum + item, 0 // starting value ); |
1 2 3 4 5 6 |
const grades = [60, 55, 80, 90, 99, 92, 75, 72]; const total = grades.reduce(sum); function sum(total, grade) { return total + grade; } |
Let’s group grades into an object:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
const letterGradeCount = grades.reduce(groupByGrade, {}); function groupByGrade(resObj, grade) { const { a = 0, b = 0, c = 0, d = 0, f = 0 } = resObj; if (grade >= 90) { return {...resObj, a: a + 1} } else if (grade >= 80) { return {...resObj, b: b + 1} } else if (grade >=70) { return {...resObj, c: c + 1} } else if (grade >= 60) { return {...resObj, d: d + 1} } else { return {...resObj, f: f + 1} } } |