2631. Group By
Enhance all arrays in JavaScript so that you can call array.groupBy(fn). It should return an object grouping the items in the array based on the callback's returned key.
📄 Problem Statement
Add a method groupBy(fn) to Array.prototype. The method should:
- Call
fn(element)for each item in the array. - Group elements that return the same key into the same array.
- Return an object where each key maps to an array of grouped items.
❌ Do not use _.groupBy from Lodash or any third-party library.
💡 Example
[1,2,3,4,5].groupBy(n => n % 2 === 0 ? "even" : "odd")
// ➞ { "odd": [1, 3, 5], "even": [2, 4] }
["apple", "banana", "apricot"].groupBy(word => word[0])
// ➞ { "a": ["apple", "apricot"], "b": ["banana"] }
🧠 Explanation
The method loops through the array, applies the callback function to each element to determine its key, then pushes that element into the correct array inside a result object.
If the key hasn't been seen before, initialize it with an empty array first.
✅ Your Solution
/**
* @param {Function} fn
* @return {Object}
*/
Array.prototype.groupBy = function(fn) {
const result = {};
for (const item of this) {
const key = fn(item);
if (!result[key]) {
result[key] = [];
}
result[key].push(item);
}
return result;
};