First of all, sorry that my question is noobish. I am self learning Javascript and I don't really understand the error.
var centuryGroup = grouping(ancestry, function(person){
return Math.ceil(person.died/100);
});
function grouping(array, group){
var groups = {};
array.forEach(function(element) {
var groupName = group(element);
if(groupName in groups){
groups[groupName].push(element); //the error is stated at this line
}
else{
groups[groupName] = element;
}
});
return groups;
}
As stated at the above, the error is at
groups[groupName].push(element);
If I remove this, it works.
And, if its defined as:
function grouping(array, group) {
var groups = {};
array.forEach(function(element) {
var groupName = group(element);
if (groupName in groups)
groups[groupName].push(element);
else
groups[groupName] = [element];
});
return groups;
}
var centuryGroup = grouping(ancestry, function(person) {
return Math.ceil(person.died / 100);
});
There is no error in the second one. *the 2nd code is taken from a tutorial.
Things I have tried:
- I put the "var centuryGroup = ..." below the function grouping... and still no difference
- I have made sure the code is working when I commented out the error line
- I have removed the {} from the if and else statement and the error still there (not that I expect it to have made a difference)
*Exact error is "TypeError undefined is not a function"
I am at a loss. Thanks for the help guys
*Edit.
The contents of "array" that is passed in is
{ name: "Carolus Haverbeke" }
sex: "m"
born: 1832
died: 1905
father: "Carel Haverbeke"
mother: "Maria van Brussel"
{ name: "Emma de Milliano" }
sex: "f"
born: 1876
died: 1956
father: "Petrus de Milliano"
mother: "Sophia van Damme"
...
By the way, if its not supposed to have the "push" property, the 2nd code shouldn't be working. But it is and it is showing the desired result. *confused
SOLVED! Its my mistake in the
element <== in the first code within the else statement that should be [element]
Thanks to Pointy for pointing out that mistake for me. Its cause as he said that it is not an array and thus .push does not work. But once I put it as [element] and made it into an array, then I will be able to .push it in as an object of arrays. Thanks to all