We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Group By

Difficulty: Medium


Problem Description

Enhance all arrays to include a method array.groupBy(fn) that returns a grouped version of the array. A grouped array is an object where each key is the output of fn(arr[i]) and each value is an array of all items in the original array that generate that key.


Key Insights

  • The fn callback function will be used to determine the key for each element in the array.
  • The output will be an object, where keys are the results of the fn function applied to the array elements.
  • Each value in the object is an array of elements from the original array that correspond to each key.
  • The order of elements within each group should reflect their order in the original array.

Space and Time Complexity

Time Complexity: O(n), where n is the number of elements in the array, as we need to iterate through the array once.

Space Complexity: O(n), in the worst case, we may store all elements in the output object.


Solution

To solve this problem, we will:

  1. Create a method groupBy that takes a callback function fn.
  2. Initialize an empty object to hold the grouped results.
  3. Iterate through each element of the array, applying the fn function to determine the key.
  4. For each key, if it doesn't exist in the object, create an array for that key, then push the current element into that array.
  5. Finally, return the constructed object.

Code Solutions

Array.prototype.groupBy = function(fn) {
    const grouped = {};
    this.forEach(item => {
        const key = fn(item);
        if (!grouped[key]) {
            grouped[key] = [];
        }
        grouped[key].push(item);
    });
    return grouped;
};
← Back to All Questions