惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
GRAHAM CLULEY
S
Security @ Cisco Blogs
P
Proofpoint News Feed
Cisco Talos Blog
Cisco Talos Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Tor Project blog
WordPress大学
WordPress大学
Project Zero
Project Zero
S
Schneier on Security
P
Proofpoint News Feed
小众软件
小众软件
P
Privacy International News Feed
美团技术团队
L
LangChain Blog
Know Your Adversary
Know Your Adversary
J
Java Code Geeks
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Register - Security
The Register - Security
N
Netflix TechBlog - Medium
Microsoft Security Blog
Microsoft Security Blog
Engineering at Meta
Engineering at Meta
I
InfoQ
量子位
Vercel News
Vercel News
博客园 - 三生石上(FineUI控件)
Spread Privacy
Spread Privacy
D
DataBreaches.Net
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
U
Unit 42
P
Privacy & Cybersecurity Law Blog
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Blog of Author Tim Ferriss
Latest news
Latest news
K
Kaspersky official blog
MongoDB | Blog
MongoDB | Blog
L
LINUX DO - 热门话题
Simon Willison's Weblog
Simon Willison's Weblog
云风的 BLOG
云风的 BLOG
S
Securelist
AWS News Blog
AWS News Blog
F
Fortinet All Blogs
T
Threat Research - Cisco Blogs
Stack Overflow Blog
Stack Overflow Blog
Scott Helme
Scott Helme
Help Net Security
Help Net Security
Y
Y Combinator Blog
宝玉的分享
宝玉的分享
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
T
Tenable Blog

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
Array Grouping in JavaScript: Object.groupBy()
Dmitri Pavlutin · 2021-12-20 · via Dmitri Pavlutin Blog

Many developers appreciate Ruby programming language because of the rich standard utility libraries. For example, the array in Ruby has a huge number of methods.

JavaScript also enriches its standard library on strings and arrays step by step. For example, in a previous post, I described the new array.at() method.

Today's hero is the new array group proposal (currently at stage 3) that introduces new methods Object.groupBy() and Map.groupBy(). Their polyfills are available in core-js library.

Let's see how you may benefit from the grouping methods.

1. Object.groupBy()

You have a list of products, where each product is an object having 2 properties: name and category.


const products = [

{ name: 'apples', category: 'fruits' },

{ name: 'oranges', category: 'fruits' },

{ name: 'potatoes', category: 'vegetables' }

];


In the example above products is an array of product objects.

Now your task is to group the products by category. The result would look like this:


const groupByCategory = {

'fruits': [

{ name: 'apples', category: 'fruits' },

{ name: 'oranges', category: 'fruits' },

],

'vegetables': [

{ name: 'potatoes', category: 'vegetables' }

]

};


How would you get an array like groupByCategory from products array in JavaScript?

The usual way is by invoking the array.reduce() method with a callback function implementing the grouping logic:


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' }

// ]

// }


Open the demo.

products.reduce((acc, product) => { ... }) reduces the products array to an object of products grouped by category.

While I do consider array.reduce() method useful and powerful, sometimes its readability is not the best.

Because grouping data is an often occurring task (recall GROUP BY from SQL?) the array group proposal introduces two useful methods: Object.groupBy() and Map.groupBy().

Here's how to use Object.groupBy() to create the same grouping by category:


const groupByCategory = Object.groupBy(products, product => {

return product.category;

});

console.log(groupByCategory);

// {

// 'fruits': [

// { name: 'apples', category: 'fruits' },

// { name: 'oranges', category: 'fruits' },

// ],

// 'vegetables': [

// { name: 'potatoes', category: 'vegetables' }

// ]

// }


Object.groupBy(products, product => {...}) returns an object where properties are category names and values are arrays of category products.

Grouping using products.groupBy() requires less code and is easier to understand than using product.reduce().

Object.groupBy(array, callback) accepts a callback function that's invoked with 3 arguments: the current array item, the index, and the array itself. The callback should return a string: the group name where you'd like to add the item.


const groupedObject = Object.groupBy(array, (item, index, array) => {

// ...

return groupNameAsString;

});


2. Map.groupBy()

Sometimes you may want to use a Map instead of a plain object. The benefit of Map is that it accepts any data type as a key, but the plain object is limited to strings and symbols only.

So, if you'd like to group data into a Map, you can use the method Map.groupBy().

Map.groupBy(array, callback) works the same way as Object.groupBy(array, callback), only that it groups items into a Map instead of a plain JavaScript object.

For example, grouping the products array into a map by category name is performed as follows:


const groupByCategory = Map.groupBy(products, 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 the items of an array (similarly to GROUP BY in SQL), then welcome the new methods Object.groupBy() and Map.groupBy().

Both functions accept a callback that should return the key of the group where the current items must be inserted.

Object.groupBy() groups the items into a plain JavaScript object, while Map.groupBy() groups them into a Map instance.

If you'd like to use these functions right away, then use the polyfill provided by core-js library.