ben432rew
ben432rew

Reputation: 1902

Can't loop through JavaScript array using a for loop

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!

Upvotes: 1

Views: 1624

Answers (1)

Sean Johnson
Sean Johnson

Reputation: 5607

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)));
}

Upvotes: 5

Related Questions