Home >Web Front-end >JS Tutorial >How Can I Group JavaScript Objects by Key Using the `reduce()` Method?

How Can I Group JavaScript Objects by Key Using the `reduce()` Method?

Linda Hamilton
Linda HamiltonOriginal
2024-12-21 02:32:09778browse

How Can I Group JavaScript Objects by Key Using the `reduce()` Method?

Grouping Objects by Key Using JavaScript

Grouping an array of objects by a specific key is a common task in programming, especially when working with data sets. One efficient way to achieve this is through the reduce() method.

In JavaScript, you can follow these steps:

  1. Declare an array of objects: Let's say you have an array of car objects, similar to the example provided in the question:
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' },
];
  1. Initialize an object as the accumulator: Create an empty object that will serve as the accumulator for the reduce() method. This object will store the grouped values.
const groupedCars = {};
  1. Use reduce() to iterate over the array: Employ the reduce() method on the cars array to iterate over each object. The reduce() function takes two arguments:
  • accumulator: The object created in step 2.
  • currentElement: The current object being iterated over.
  1. Add objects to the accumulator: Within the reduce() method, check if the current make property exists as a property in the accumulator object. If it does not exist, create a new array at that property. Then, push the currentElement into the created array. This process effectively groups objects based on their make.
const groupedCars = cars.reduce((accumulator, currentElement) => {
  const make = currentElement.make;

  if (!accumulator[make]) {
    accumulator[make] = [];
  }

  accumulator[make].push(currentElement);

  return accumulator;
}, {});
  1. Return the grouped object: The reduce() method returns the accumulated object, which contains the grouped values.
  2. Log the grouped result: You can log the grouped object to the console to verify the output.
console.log(groupedCars);

This approach uses vanilla JavaScript and provides a structured way to group objects based on a specified key, creating a new object with the grouped values.

The above is the detailed content of How Can I Group JavaScript Objects by Key Using the `reduce()` Method?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn