Search⌘ K

Solution Review: Calculate Score

Explore how to solve a calculation challenge by applying JavaScript's filter and reduce methods. Understand filtering array elements by condition and reducing arrays to a single value. This lesson helps you grasp higher-order functions to compute scores effectively.

We'll cover the following...

Solution #

Javascript (babel-node)
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. ...