๐ง๐ต๐ฒ ๐๐ฎ๐๐ ๐ช๐ฎ๐ ๐ง๐ผ ๐๐ป๐ฑ๐ฒ๐ ๐ฎ๐ป๐ฑ ๐ข๐ฟ๐ด๐ฎ๐ป๐ถ๐๐ฒ ๐๐ฎ๐๐ฎ ๐ถ๐ป ๐๐ฎ๐๐ฎ๐ฆ๐ฐ๐ฟ๐ถ๐ฝ๐ You need to organize arrays of objects. You can use reduce to do this. But reduce can make code complex and hard to understand.
Good news: there's a simpler way to do this using Object.groupBy and Map.groupBy methods.
- These methods help you group data by a key.
- They make your code more readable and easier to understand.
Why group data?
- Grouping data improves performance.
- It makes searches and data consumption easier.
Here's an example: You have a list of products. You want to group them by category. You can use Object.groupBy to do this:
const products = [
{ name: "iPhone", category: "electronics", price: 5000 },
{ name: "Laptop", category: "electronics", price: 3000 },
{ name: "T-shirt", category: "clothing", price: 50 },
{ name: "Pants", category: "clothing", price: 120 },
];
const productsByCategory = Object.groupBy(products, (product) => product.category);
Map.groupBy handles cases where the key is not a string.
- It preserves the original type of the key.
- It avoids automatic conversions and ambiguities.
These new grouping methods simplify your development routine.
- They make your code leaner and more expressive.
- They are widely supported in modern browsers.
Source: https://dev.to/sucodelarangela/groupby-in-javascript-the-easy-way-to-index-and-organize-data-53op