Home >Web Front-end >JS Tutorial >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:
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 = {};
const groupedCars = cars.reduce((accumulator, currentElement) => { const make = currentElement.make; if (!accumulator[make]) { accumulator[make] = []; } accumulator[make].push(currentElement); return accumulator; }, {});
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!