isotropic-2022
Share
Blog
Search
Menu

What is the Most Efficient Way to groupby Objects in an Array? - JS Tutorial

By James LePage
|
Last updated on November 6th, 2022
|

JavaScript is a great language with many features. The community is constantly growing and the language itself gets regular updates. Despite having so many features built into the language itself, there are still many tasks that you need some custom JavaScript to do.

What does “group by” accomplish?

Working with any sort of data in JavaScript likely means you are dealing with an array of objects, perhaps from an external API. Let’s say for example there is an Animals API that returns an array of data like this:

[
  { name: "penguin", size: "medium", diet: "carnivore" },
  { name: "elephant", size: "large", diet: "herbivore" },
  { name: "wolf", size: "medium", diet: "carnivore" },
  { name: "sheep", size: "medium", diet: "herbivore" },
  { name: "skunk", size: "medium", diet: "omnivore" },
  { name: "ant", size: "small", diet: "omnivore" },
  { name: "rabbit", size: "small", diet: "herbivore" },
  { name: "blue whale", size: "large", diet: "carnivore" },
];Code language: JavaScript (javascript)

You may want to query this data and see, for example, all the large animals or maybe all of the carnivorous animals. Instead, you could also group the entire data set by size to get effectively a list of lists organized by size. This can be helpful if you do not want to keep querying that data over and over. Now let’s take a look at how to do this in JavaScript.

How to do it

Since ES6 has been out for a while let’s focus on a solution that uses the ES6 Map (the object, not to be confused with the array function). Maps are useful because they can store key-value pairs which you can then use to quickly look up those values. For group by, we will want the keys in the Map to be each available value for whatever we’re grouping by. In the above example, if we’re grouping by size, the keys of the Map should be “small”, “medium”, and “large”.

The values of the Map should be arrays containing each of the animals that match with the given value. The solution is actually quite straightforward:

function groupBy(items, key) {
  // initialize our map
  const map = new Map();
  items.forEach((item) => {
    // get the value we're grouping by
    const keyValue = item[key];
    // get the array of items for this key value. default to an empty array
    const currArr = map.has(keyValue) ? map.get(keyValue) : [];
    // add the current item
    currArr.push(item);
    // update the array
    map.set(keyValue, currArr);
  });
  return map;
}Code language: JavaScript (javascript)

As you might expect, here are the results when using the Animals API dataset above and grouping by diet:

js_upload_

Conclusion

I once received advice from a peer about what to do when you don’t know how to solve something in JavaScript. He said to “always just use a map” and as you can see group by is no different. There are many different solutions out there to fine tune the performance though so if you have any alternatives or improvements feel free to leave a comment.

The Isotropic Codex is a collection of code snippets and education for WordPress, web and WooCommerce developers.
Subscribe & Share
If you liked this content, subscribe for our monthly roundup of WordPress news, website inspiration, exclusive deals and interesting articles.
Unsubscribe at any time. We do not spam and will never sell or share your email.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Article By
James LePage
Contributors/Editors
notloggedin
James LePage is the founder of Isotropic, a WordPress education company and digital agency. He is also the founder of CodeWP.ai, a venture backed startup bringing AI to WordPress creators.
We're looking for new authors. Explore Isotropic Jobs.
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram