How can I group an array of objects by key?
To group objects by key in JavaScript, the reduce()
method is often used to assemble items into clusters. Here’s a quick and efficent solution to accomplish this:
This groupBy
function returns an object that consists of properties representing unique group names (e.g. 'dog', 'cat') and the associated array of objects belonging to that group.
Introducing Reduce
The reduce
function is a powerful tool used to condense the array elements into a single cumulative result. It works by traversing the array from left to right and applying a function to each element.
In our case, we are accumulating an object, where each property corresponds to the value of a unique key in our array elements. The value of each property is an array of elements that share the same key.
Working with absent keys
In a situation where some objects in your array might not contain the key you're grouping by, you can filter out such objects before the reduce
operation. This prevents the possibility of trying to access properties from undefined
.
Simplification courtesy of ES6
Modern JavaScript syntax (ES6+) offers ways to make our code more concise and readable. Leveraging arrow functions, default parameters, and optional chaining, we can make our groupBy function a neat one-liner:
The lodash alternative
If you love external libraries, lodash got you covered with a convenient _.groupBy()
function:
Our friend lodash doesn't stop there. If you need to shape-shift the grouped results, _.mapValues()
can be very useful to transform the grouped object values:
Going deeper: Duplicates, Clean Objects and Merging
Handling duplicates
If your data has reoccuring keys, make sure the final object structure eliminates duplicate keys. You can handle duplicates using either ES6 features like Set
or lodash's .omit
.
Embrace clean objects
Starting your reduction with an object? Go for Object.create(null)
for a fresh, empty object that doesn't inherit properties from Object.prototype
.
Uniting grouped objects
Merging grouped objects into one. No problem! You can use Object.assign
for that fine piece of object composition.
Practical examples and custom variations
Sorting the groups
After grouping, you can sort the resulted object by its keys:
Grouping by multiple keys
Sometimes, you might want to group by multiple keys. Fear not, it's also possible!
Dynamic property grouping
You can also group by properties that are determined by a dynamic function:
Was this article helpful?