2631. Group By

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.

A 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:

Example 2:

Example 3:

Constraints:

  • 0 < = a r r a y . l e n g t h < = 1 0 5 0 <= array.length <= 10^5 0<=array.length<=105
  • fn returns a string

From: LeetCode
Link: 2631. Group By


Solution:

Ideas:
The core idea behind this groupBy implementation is:
1. Create an empty result object to hold the grouped data.
2. Iterate over the array.
3. For each item, call the fn callback function to get the key for that item.
4. If that key already exists in the result object, push the item into the array for that key.
5. If that key does not exist yet, create a new array in that key position and push the item into it.
6. Return the final result object with all the grouped data.
So it’s basically aggregating all the array items into groups based on the keys returned by the callback function. The power of this approach is that you can group the data based on any logic or calculation in the callback function.
The time complexity of this approach is O(n) since we have to iterate the entire array of n elements once. The space complexity is O(n) as well since in the worst case we create n groups.
Code:
/**
 * @param {Function} fn
 * @return {Array}
 */
Array.prototype.groupBy = function(fn) {
    let result = {};
    for (let i = 0; i < this.length; i++) {
        let key = fn(this[i]);
        if (!result[key]) {
            result[key] = [];
        }
        result[key].push(this[i]);
    }
    return result;
};

/**
 * [1,2,3].groupBy(String) // {"1":[1],"2":[2],"3":[3]}
 */
05-28 20:03