2631. Group By
Enhancing JavaScript Arrays with a Custom groupBy
Method
In the world of JavaScript, extending native prototypes can often make our code more efficient and readable. Today, I'm excited to share a method to group array elements based on a function you provide. This custom groupBy
method is simple yet powerful, leveraging the capabilities of JavaScript's array methods.
The Problem
Grouping elements in an array is a common task in many applications. For example, given the array [1, 2, 3]
and the grouping function String
, we want the output to be:
{"1":[1],"2":[2],"3":[3]}
To achieve this, we will create a custom groupBy
method that categorizes array elements efficiently.
The Solution
Here’s the code for our groupBy
method:
/**
* @param {Function} fn
* @return {Object}
*/
Array.prototype.groupBy = function(fn) {
return this.reduce((group, item) => {
const key = fn(item);
if (!group[key]) {
group[key] = [];
}
group[key].push(item);
return group;
}, {});
};
/**
* Example:
* [1,2,3].groupBy(String) // {"1":[1],"2":[2],"3":[3]}
*/
Intuition
The idea behind this solution is to use JavaScript's reduce
method to build an object that groups elements. By applying the provided function to each element, we determine the key for each group and categorize elements accordingly. This approach ensures efficiency by iterating through the array just once.
Approach
Adding the Method: Extend
Array.prototype
with agroupBy
method, making it available to all array instances.Using
reduce
: Utilize thereduce
function to iterate over the array and construct a grouped object.Generating Keys: Apply the function
fn
to each element to determine the grouping key.Grouping Elements: Initialize an array for the key if it doesn't exist and push the current element into the corresponding group.
Returning the Grouped Object: The final grouped object is returned, containing arrays of grouped elements.
Example Usage
Here's how you can use the groupBy
method:
let arr = [1, 2, 3];
let result = arr.groupBy(String);
console.log(result);
// Output: {"1":[1],"2":[2],"3":[3]}
Complexity Analysis
Time Complexity: O(n), where n is the number of elements in the array. This efficiency is achieved by iterating through the array once.
Space Complexity: O(n), due to the space required to store the grouped elements.
Conclusion
Extending Array.prototype
with a groupBy
method provides a flexible and efficient way to categorize array elements. By harnessing the power of reduce
, we can group data based on custom logic with minimal effort. This method is versatile, useful for various scenarios where data needs to be organized or categorized.
For a more detailed explanation and other solutions, check out my LeetCode Solution and stay tuned for more tips and tricks!
Happy coding! š
Comments
Post a Comment