| Implement a function groupBy(items, key) that groups an array of objects by a property and
|
| returns an object where keys are group identifiers and values are arrays of the grouped items.
|
|
|
| Note:
|
| The key will always be a string.
|
| Do not mutate the original array.
|
|
|
| function groupBy(items, key) {}
|
|
|
| // Example
|
| const products = [
|
| { id: 101, category: 'electronics', name: 'Laptop', price: 1200 },
|
| { id: 102, category: 'electronics', name: 'Smartphone', price: 800 },
|
| { id: 103, category: 'furniture', name: 'Chair', price: 150 },
|
| { id: 104, category: 'furniture', name: 'Table', price: 300 },
|
| { id: 105, category: 'clothing', name: 'T-Shirt', price: 20 },
|
| { id: 106, category: 'clothing', name: 'Jeans', price: 40 }
|
| ];
|
|
|
| // Usage
|
| console.log(groupBy(products, 'category'));
|
|
|
| // {
|
| // electronics: [
|
| // { id: 101, category: 'electronics', name: 'Laptop', price: 1200 },
|
| // { id: 102, category: 'electronics', name: 'Smartphone', price: 800 }
|
| // ],
|
| // furniture: [
|
| // { id: 103, category: 'furniture', name: 'Chair', price: 150 },
|
| // { id: 104, category: 'furniture', name: 'Table', price: 300 }
|
| // ],
|
| // clothing: [
|
| // { id: 105, category: 'clothing', name: 'T-Shirt', price: 20 },
|
| // { id: 106, category: 'clothing', name: 'Jeans', price: 40 }
|
| // ]
|
| // }
|