Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Refactoring a Javascript function

Hi everyone,

I have multiple function like those ones

let getMaleStudent = schools.map(school => {
    return getNumber(school.p1.people.students.male)
}).reduce((count, total) => count+=total)

let getFemaleStudent = schools.map(school => {
    return getNumber(school.p1.people.students.female)
}).reduce((count, total) => count+=total)

My problem is I would like to refactor with one function like

const getTest = (val) => {
    schools.map(school => {
        return getNumber(val)
    }).reduce((count, total) => count+=total)
}

let getMaleStudent = getTest('school.p1.people.students.male')

But this example doesn't work.

Does anybody have an idea of how I could proceed?

Jamie Carter
seal-mask
.a{fill-rule:evenodd;}techdegree
Jamie Carter
Front End Web Development Techdegree Student 12,096 Points
getTotalStudentsByGender(school, gender){
    return = schools.map(school => {
        return getNumber(school.p1.people.students[gender])
    }).reduce((count, total) => count+=total)
}

then using

getTotalStudentsByGender(school, 'male')
getTotalStudentsByGender(school, 'female')

alternatively you could return the function with an object containing both.

getTotalStudentsByGender(school){
    const genderNumber = {}
    genderNumber.male  = schools.map(school => {
        return getNumber(school.p1.people.students.male)
    }).reduce((count, total) => count+=total)

    genderNumber.female = schools.map(school => {
        return getNumber(school.p1.people.students.female)
    }).reduce((count, total) => count+=total)
    return genderNumber
}
getTotalStudentsByGender(school)

1 Answer

Thanks a lot works wonders. Thing is that in this case I needed to use [value] with square brackets to access the value or my property.