Grouping Arrays of Objects by Key

Grouping arrays of objects by a common key is a frequent task in JavaScript programming. This operation involves categorizing objects based on a specific property and organizing them into separate groups. In this tutorial, we will explore how to achieve this using vanilla JavaScript, as well as with the help of popular libraries like Lodash.

Understanding the Problem

Imagine you have an array of car objects, each containing properties like make, model, and year. Your goal is to group these cars by their make property, resulting in an object where each key represents a unique make and its corresponding value is an array of car objects belonging to that make.

Solution Using Vanilla JavaScript

One approach to solve this problem is by utilizing the Array.prototype.reduce() method. This method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single output value.

const cars = [
  { make: 'audi', model: 'r8', year: '2012' },
  { make: 'audi', model: 'rs5', year: '2013' },
  { make: 'ford', model: 'mustang', year: '2012' },
  { make: 'ford', model: 'fusion', year: '2015' },
  { make: 'kia', model: 'optima', year: '2012' }
];

const groupedCars = cars.reduce((acc, car) => {
  if (!acc[car.make]) {
    acc[car.make] = [];
  }
  // Remove the 'make' property from each car object before adding it to the group
  const { make, ...rest } = car;
  acc[car.make].push(rest);
  return acc;
}, {});

console.log(groupedCars);

This will output an object where each key is a unique make and its value is an array of objects containing the model and year for cars of that make.

Using Lodash

For those familiar with or using Lodash in their projects, the groupBy function provides a straightforward way to achieve the same result:

const _ = require('lodash');

const cars = [
  { make: 'audi', model: 'r8', year: '2012' },
  { make: 'audi', model: 'rs5', year: '2013' },
  { make: 'ford', model: 'mustang', year: '2012' },
  { make: 'ford', model: 'fusion', year: '2015' },
  { make: 'kia', model: 'optima', year: '2012' }
];

const groupedCars = _.groupBy(cars, 'make');

// To remove the 'make' property from each car object
const result = _.mapValues(groupedCars, (clist) => clist.map((car) => _.omit(car, 'make')));

console.log(result);

Modern JavaScript Approach

With modern JavaScript, you can also use Object.groupBy if it’s available in your environment or polyfill it:

const cars = [
  { make: 'audi', model: 'r8', year: '2012' },
  { make: 'audi', model: 'rs5', year: '2013' },
  { make: 'ford', model: 'mustang', year: '2012' },
  { make: 'ford', model: 'fusion', year: '2015' },
  { make: 'kia', model: 'optima', year: '2012' }
];

const groupedCars = Object.groupBy(cars, (car) => car.make);

// Adjust the grouping to exclude the 'make' property
const result = Object.fromEntries(Object.entries(groupedCars).map(([key, value]) => [
  key,
  value.map(({ make, ...rest }) => rest)
]));

console.log(result);

Conclusion

Grouping arrays of objects by a common key is a versatile operation that can be accomplished in various ways depending on your project’s requirements and the libraries you’re using. Whether you opt for vanilla JavaScript solutions or leverage utilities from Lodash, understanding these approaches will help you tackle data manipulation tasks with ease.

Leave a Reply

Your email address will not be published. Required fields are marked *