Array grouping in JavaScript: array groupBy()
Original text: https://dmitripavlutin.com/ja...
Due to the rich library of standard utilities, many developers prefer the Ruby programming language. For example, Arrays in Ruby There are a lot of ways.
JavaScript has also gradually enriched its standard library of strings and arrays. For example, in the previous article, I described the new array.at() method.
Today's protagonist is new Array group proposal (currently in phase 3), it introduces a new method, array Groupby() and array groupByToMap(). their polyfills Available in the core JS library.
Let's see how you can benefit from the grouping approach.
1.array.groupBy ()
You have a list of products, where each product is an object with two attributes: name and category.
const products = [ { name: 'apples', category: 'fruits' }, { name: 'oranges', category: 'fruits' }, { name: 'potatoes', category: 'vegetables' } ];
In the above example, products is an array of product objects.
Now you must perform a simple operation on the product list -- grouping products by category.
const groupByCategory = { 'fruits': [ { name: 'apples', category: 'fruits' }, { name: 'oranges', category: 'fruits' }, ], 'vegetables': [ { name: 'potatoes', category: 'vegetables' } ] };
How do you get an array of products from an array in groupByCategory?
The usual method is array Reduce() calls the method with the correct callback function:
const groupByCategory = products.reduce((group, product) => { const { category } = product; group[category] = group[category] ?? []; group[category].push(product); return group; }, {}); console.log(groupByCategory); // { // 'fruits': [ // { name: 'apples', category: 'fruits' }, // { name: 'oranges', category: 'fruits' }, // ], // 'vegetables': [ // { name: 'potatoes', category: 'vegetables' } // ] // }
products. reduce((acc, product) => { ... }) Simplify the products array to product objects grouped by category.
Although I do think array The reduce () method is useful and powerful, but sometimes its readability is not the best.
Because grouping data is a frequent task (GROUP BY recalls from SQL?), Array group proposal Two useful methods are introduced: array Groupby() and array groupByToMap().
The following is array Groupby() method to create the same group by category:
const groupByCategory = products.groupBy(product => { return product.category; }); console.log(groupByCategory); // { // 'fruits': [ // { name: 'apples', category: 'fruits' }, // { name: 'oranges', category: 'fruits' }, // ], // 'vegetables': [ // { name: 'potatoes', category: 'vegetables' } // ] // }
products. groupBy(product => {...}) Returns an object with the key of each attribute as the category name and the value as an array containing the products of the corresponding category.
Group usingproducts Groupby () requires less code than using and is easier to understand product reduce().
array.groupBy(callback) accepts a callback function called with three parameters: the current array item, the index, and the array itself. The callback should return a string: the name of the group in which you want to add the item.
const groupedObject = array.groupBy((item, index, array) => { // ... return groupNameAsString; });
2.array.groupByToMap ()
Sometimes you might want to use a Map instead of a normal object, because a Map accepts any data type as a key, but pure objects are limited to strings and symbols.
Therefore, if you want to group data into a Map, you can use this method array groupByToMap().
array.groupByToMap(callback) works exactly the same as array Groupby (callback), which just groups items into maps instead of ordinary JavaScript objects.
For example, group the products array into a map by category name, as follows:
const groupByCategory = products.groupByToMap(product => { return product.category; }); console.log(groupByCategory); // Map([ // ['fruits', [ // { name: 'apples', category: 'fruits' }, // { name: 'oranges', category: 'fruits' }, // ]], // ['vegetables', [ // { name: 'potatoes', category: 'vegetables' } // ] // ])
3, Conclusion
If you want to easily group items in an array (similar to GROUP BYSQL), welcome to the new method array Groupby() and array groupByToMap().
Both functions accept a callback that should return the key of the group that must be inserted into the current project.
array.groupBy() combines items into a common JavaScript object, while array Groupbytomap () combines them into a Map instance.