Explorer
Node.js

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; }, {}); } ```

Group Array by Property

Easy
Write a function `groupBy(arr, key)` that groups array objects by the given key.
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
{"IT":[{"name":"A","dept":"IT"},{"name":"C","dept":"IT"}],"HR":[{"name":"B","dept":"HR"}]}