[Medium] LeetCode JS 30 - 2631. Group By

March 7, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

LeetCode 30 Days of JavaScript

This question is from LeetCode's 30 Days of JavaScript Challenge

2631. Group By

Question Prompt

Write code that enhances all arrays such that you can call the array.groupBy(fn) method on any array and it will return a grouped version of the array.

grouped array is an object where each key is the output of fn(arr[i]) and each value is an array containing all items in the original array with that key.

The provided callback fn will accept an item in the array and return a string key. The order of each value list should be the order the items appear in the array. Any order of keys is acceptable.

Please solve it without lodash's _.groupBy function.

// Example 1:
Input:
array = [
  {"id":"1"},
  {"id":"1"},
  {"id":"2"}
],
fn = function (item) {
  return item.id;
}
Output:
{
  "1": [{"id": "1"}, {"id": "1"}],
  "2": [{"id": "2"}]
}
Explanation:
Output is from array.groupBy(fn).
The selector function gets the "id" out of each item in the array.
There are two objects with an "id" of 1. Both of those objects are put in the first array.
There is one object with an "id" of 2. That object is put in the second array.

Solutions

First, we add the groupBy to Array.prototype by assigning a function to Array.prototype.groupBy = function(fn) { ... }. This modifies the built-in blueprint for all arrays, injecting our new groupBy capability.

Within the function , we create an empty object to store the groups by const grouped = {};. Then, we use forEach to loop through every item in the array (this refers to the array itself).

const key = fn(item) is where the magic happens! Your provided function (fn) determines the group key for the current item. If it's a new group (the key doesn't exist in our object), we create an empty array to hold items in that group. We then add the item to its corresponding group array.

After the loop, we return the grouped object.

Array.prototype.groupBy = function (fn) {
  const grouped = {}; // The object to store our groups

  this.forEach((item) => {
    const key = fn(item); // Get the group key for this item
    // Create the group array if it doesn't exist
    if (!grouped[key]) {
      grouped[key] = [];
    }
    grouped[key].push(item); // Add the item to its group
  });
  return grouped;
};
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee