Solution Review: Calculate Score

This lesson will explain the solution to the problem in the previous lesson.

We'll cover the following...

Solution #

Press + to interact
function boySum(records){
const ans = records.filter(({gender}) => gender === 'BOYS')
var out = ans.reduce((sum, records) => sum +records.value,0)
return out
}
const records = [
{
value: 55,
gender: "BOYS"
},
{
value: 10,
gender: "BOYS"
},
{
value: 85,
gender: "GIRLS"
},
{
value: 12,
gender: "GIRLS"
},
{
value: 70,
gender: "BOYS"
}
]
console.log(boySum(records))

Explanation #

To solve this challenge, we make use of two higher-order functions, filter and reduce. Before we discuss the code, let’s understand these functions.

filter: takes a callback function as a parameter and returns a new array containing all the elements from the given array that satisfy the condition set by this function. It also takes an optional parameter, the value thisArg, which specifies the value of this to use when executing the callback. ...