I just recently picked up JS and have been working on an exercise to sort people from an array of records, ancestry
, into the centuries they lived in and their ages. Here's a sample element from ancestry
:
{
name: "Carolus Haverbeke"
sex: "m"
born: 1832
died: 1905
father: "Carel Haverbeke"
mother: "Maria van Brussel"
}
Here's my attempt:
ancestry.forEach(function(person) {
var ages = {};
var century = Math.ceil(person.died / 100);
if (century in ages)
ages[century].push(person.died - person.born);
else
ages[century] = person.died - person.born;
});
This is the general format I'm trying to store in ages
, which maps each century to an array of the people's ages:
{
16: [24, 51, 16]
17: [73, 22]
18: [54, 65, 28]
}
I'm really confused as this code only saves the first person in ancestry
into ages
. I thought it might be because I defined ages
inside the forEach
, but when I move var ages = {}
outside I get this:
TypeError: ages[century].push is not a function (line 18)
Could someone please help explain what's going on and the code should be fixed?