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
Erwan EL
7,669 PointsRefactoring 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?
1 Answer
Erwan EL
7,669 PointsThanks 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.
Jamie Carter
Front End Web Development Techdegree Student 12,096 PointsTo use a set field of an object use object.thingname, but to use a variable as the name use object[variable]
Jamie Carter
Front End Web Development Techdegree Student 12,096 PointsHmm, did this answer your question, I dont understand that last sentence?
Jamie Carter
Front End Web Development Techdegree Student 12,096 PointsJamie Carter
Front End Web Development Techdegree Student 12,096 Pointsthen using
alternatively you could return the function with an object containing both.
getTotalStudentsByGender(school)