-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmotherChildAgeDifference.js
More file actions
44 lines (34 loc) · 1.14 KB
/
motherChildAgeDifference.js
File metadata and controls
44 lines (34 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/* Mother-child age difference */
/*
Using the example data set from this chapter, compute the average age difference between mothers and children (the age
of the mother when the child is born). You can use the average function defined earlier in this chapter.
Note that not all the mothers mentioned in the data are themselves present in the array. The byName object, which makes
it easy to find a person’s object from their name, might be useful here.
*/
function average(array) {
function plus(a, b) { return a + b; }
return array.reduce(plus) / array.length;
}
var byName = {};
ancestry.forEach(function(person) {
byName[person.name] = person;
});
// Your code here.
function average(array) {
function plus(a, b) { return a + b; }
return array.reduce(plus) / array.length;
}
var byName = {};
ancestry.forEach(function(person) {
byName[person.name] = person;
});
// Your code here.
var hasKnownMother = function(person) {
return person.mother in byName;
};
function getAgeDiff(person) {
return person.born - byName[person.mother].born;
}
console.log(average(ancestry.filter(hasKnownMother).map(getAgeDiff)));
// → 31.2
// → 31.2