Great, new JavaScript proposal: array groupBy()

Posted by prasitc2005 on Wed, 12 Jan 2022 01:24:29 +0100

Author: Ashish Lahoti
Translator: front end Xiaozhi
Source: dmitripavlutin

Many developers like the ruby programming language because it has a rich library of standard utilities. For example, arrays in Ruby have a large number of methods.

However, our JavaScript is also working hard to gradually enrich its standard library in terms of strings and arrays. For example, in the previous article, we introduced the new array At() method.

Today we are looking at the new array group proposal (currently in the third stage), which introduces a new method array Groupby () and array groupbytomap() . Their polyfills The file can be found in the core JS library.

Next, let's see what we can learn from it.

1. array.groupBy()

Suppose we 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, perform a simple operation on the product list to group products by category.

const groupByCategory = {
  'fruits': [
    { name: 'apples', category: 'fruits' }, 
    { name: 'oranges', category: 'fruits' },
  ],
  'vegetables': [
    { name: 'potatoes', category: 'vegetables' }
  ]
};

How to get an array similar to groupByCategory from the products array?

The usual method is to use array Reduce(), as shown below:

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) => { ... }) Restore the product array to a product object grouped by category.

array. The reduce () method is useful and powerful, but sometimes its readability is not the best.

Because grouping data is common (recall groupby from SQL?), The array group proposal introduces two useful methods: array Groupby() and array groupByToMap().

The following describes how to use array Groupby() creates the same classification group:

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 in which the key of each attribute is the category name and the value is the product array of the corresponding category.

Using products Groupby() is better than using product Reduce () has less code and is easier to understand.

array.groupBy(callback) accepts a callback function. When the function is called, it has three parameters: the current array item, the index and the array itself. The callback function should return a string: the group name of the project you want to add.

const groupedObject = array.groupBy((item, index, array) => {
  // ...
  return groupNameAsString;
});

2. array.groupByToMap()

Sometimes you may want to use maps instead of ordinary objects. The advantage of Map is that it can accept any data type as a key, but ordinary objects are limited to strings and symbol s.

Well, if you want to group data into a Map, you can use array Groupbytomap() method.

array.groupByToMap(callback) works the same way as array Groupby (callback) is exactly the same, except that it groups items into a Map instead of an ordinary JS object.

For example, the product array is grouped into an ap by category name. The execution method is 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. Summary

If you want to easily group items in an array (similar to GROUP BY in SQL), you are welcome to use the new method array Groupby() and array groupByToMap().

Both functions accept a callback function that returns the key of the group that must be inserted into the current item.

array.groupBy() groups these items into a common JavaScript object, while array Groupbytomap() groups them into a Map instance.

If you want to use these functions right away, use polyfill provided by the core JS library.

The possible bugs in editing cannot be known in real time. Afterwards, in order to solve these bugs, we spent a lot of time on log debugging. By the way, we recommend a useful bug monitoring tool Fundebug.

Original text: https://dmitripavlutin.com/ja...

communication

There are dreams and dry goods. Wechat search [Daqian world] pays attention to this bowl washing wisdom who is still washing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi It has been included. There are complete test sites, materials and my series of articles for the interview of front-line large factories.

Topics: Javascript Front-end