arrays - Eloquent Javascript Exercise 5.2. Help organizing thoughts -
question prompt: using example data set chapter, compute average age difference between mothers , children (the age of mother when child born). can use average function defined earlier in chapter.
note not mothers mentioned in data present in array. byname object, makes easy find person’s object name, might useful here.
js file: http://eloquentjavascript.net/code/ancestry.js
my approach
create object "mothers" keys, arrays containing "mother's dob, daughter's name, daughter's dob".
calculate mother's age when having baby "daughter's dob" - "mother's dob"
pass values average function provided, written as
function average(array) { function plus(a, b) { return + b; } return array.reduce(plus) / array.length; }
i'm stuck @ step 1
step 1 - split sub-steps
a. remove data points mother = null && mother's dob unknown (her name listed "mother", there no separate entry her)
filter out "null" entries: var hasmom = ancestry.filter(function(person) { return person.mother != null;}); map array of mother names:
var momset = hasmom.map(function(person) {return person.mother;}); create function test if entry contained within set
function isinset(set, person) {return set.indexof(person.name) > -1}; apply function in filter
var hasknownmother = hasmom.filter(function(person) {return isinset(momset, person)}); b. create byname object of these mothers daughter , dob
var byname = {}; hasknownmother.foreach(function(person) { byname[person.name] = [person.born, person.mother];}); question: @ point, i've filtered out 34 entries 10. cross-checking names , entries, not getting results intended.
what doing incorrectly? should rethink?
c. search .js file mother's name, add(push?) dob byname object
question: have no idea if want search byname object's keys (mother names), match them ancestry .js database keys, , add .js's dob entry byname object.
i'm thinking in loop, or bind?
i think efficient way build hash of people using name key you're not iterating. after that, can iterate original array again, time checking mother exists in data , pushing difference output array go.
var ancestryjson = json.parse(ancestry_file), byname = {}, agedifferences = []; function initnamehash(){ for(var = 0, len = ancestryjson.length; < len; i++){ byname[ancestryjson[i].name] = ancestryjson[i]; } } function setagedifferences(){ for(var = 0, len = ancestryjson.length; < len; i++){ var child = ancestryjson[i]; if(child.mother !== null && byname[child.mother] !== undefined){ var mother = byname[child.mother]; var agedifference = child.born - mother.born; agedifferences.push(agedifference); } } } function average(array) { function plus(a, b) { return + b; } return array.reduce(plus) / array.length; } initnamehash(); setagedifferences(); console.log(agedifferences); alert(average(agedifferences)); check fiddle: https://jsfiddle.net/oafd8hgl/
Comments
Post a Comment