Write a function `groupBy(arr, key)` that groups array objects by the given key.
Problem Statement
Write a function `groupBy(arr, key)` that groups array objects by the given key.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Use reduce to build an object where each key maps to an array of matching items.
š” Hint 2:
For each item, get the grouping value with item[key].
š” Hint 3:
acc[groupVal] = [...(acc[groupVal] || []), item]; return acc;
ā
Solution:
```javascript
function groupBy(arr, key) {
return arr.reduce((acc, item) => {
const group = item[key];
acc[group] = [...(acc[group] || []), item];
return acc;
}, {});
}
```