1

I'm going through the book Eloquent Javascript, and I'm doing an exercise where I'm having trouble understand what I'm doing wrong. Here is code that computes the averages correctly(ancestry is a JSON object):

function average(array) {
  function plus(a, b) { return a + b; }
  return array.reduce(plus) / array.length;
};

function age(p) { return p.died - p.born; };

function groupBy(array, action){
  var groups = {};
  array.forEach(function(individual){
    var group = action(individual);
    if (groups[group] == undefined)
      groups[group] = [];
    groups[group].push(individual);
  });
  return groups;
};

var centuries = groupBy(ancestry, function(person){
  return Math.ceil(person.died / 100);
});

console.log(average(centuries[16].map(age)));
console.log(average(centuries[17].map(age)));
console.log(average(centuries[18].map(age)));
console.log(average(centuries[19].map(age)));
console.log(average(centuries[20].map(age)));
console.log(average(centuries[21].map(age)));
// → 16: 43.5
//   17: 51.2
//   18: 52.8
//   19: 54.8
//   20: 84.7
//   21: 94

Which is all fine and well. However, for the life of me I could not figure out how to write code that would not require the multiple console.log calls at the end. Here is the closest I could seem to come up with, but I kept getting a typeError and I don't understand why.

for (century in centuries) {
  console.log(average(century.map(age)));
};

Why doesn't this for in loop work? Thanks in advance!

3
  • 6
    Century is a key, not an object. You need something like centuries["century"] Commented Aug 4, 2014 at 0:27
  • 4
    @Gary without the quotes Commented Aug 4, 2014 at 0:32
  • Thanks @Gary! That cleared it up for me. Commented Aug 4, 2014 at 0:40

1 Answer 1

5

for..in loops in Javascript store the key value in the variable you pass.

for (century in centuries) {
    //here, century is the key (16, 17, etc)
    //not the value of the entry in the array
    console.log(average(centuries[century].map(age)));
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.