2

I'm very new to JavaScript and I have been working through the Eloquent JavaScript (2nd) exercises in order to learn more. One particular exercise (5.3) has been giving me a lot of trouble.

The goal of the exercise is to take an array of objects that contains the date of death for a variety of people and group them by century based on death date. This is what I have so far:

function groupBy(array, groupOf) {
  var groups = {};
  array.forEach(function(element) {
    var groupName = groupOf(element);
    if (groupName in groups)
      groups[groupName].push(element);
    else
      groups[groupName] = element;
  });
  return groups;
}

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

I believe the problem can be narrowed down to this line: groups[groupName] = element; but I don't understand why this is wrong.

Thanks for the help. I apologize in advance if this is obvious.

1 Answer 1

2

You need to create an array in this line

groups[groupName] = element;

instead you are just assigning the object. Since objects don't have push method, your code is failing. You can create an array, like this

groups[groupName] = [element];

Also, you can use the shorthand notation to write the if..else condition, like this

groups[groupName] = groups[groupName] || [];
groups[groupName].push(element);

Or, you can simply write an if condition, like this

if (groupName in groups === false) {
    groups[groupName] = [];
}
groups[groupName].push(element);

Both the if condition and the groups[groupName] || [] makes sure that, groups[groupName] has an empty array, if groupName does not exist in groups.

groups[groupName] = groups[groupName] || [];

Here, groups[groupName] will be evaluated to undefined if groupName is not found in groups, which is actually falsy. Since the first expression is falsy, the second expression [] will be the result of the right hand side. So, if the groupName doesn't exist, then an empty array will be assigned to groups[groupName].

Sign up to request clarification or add additional context in comments.

Comments

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.