DEV Community

Discussion on: Frontend interview - Questions I was asked

Collapse
 
infantiablue profile image
Truong Phan • Edited

I may use the implicit variables so that you could read easily, see my comments for the explanations

// get the input property to group by, we attach the function to the prototype object
Array.prototype.groupBy = function (prop) {
    // then apply reduce
    return this.reduce((group, item) => {
        // create new property for the group object if not existed, if yes, reassign from the accumulator 
        group[item[prop]] = group[item[prop]] || [];
        // add new item to the group of property (in this  case, a list) we want to group
        group[item[prop]].push(item);
        return group;
   // create initial empty object to implement reduce
    }, {});
};
Enter fullscreen mode Exit fullscreen mode

Then we can use people.groupBy('gender') or people.groupBy('age')