Home > Web Front-end > JS Tutorial > How Can Lodash's `_.groupBy` Function Efficiently Group Arrays of Objects by Key?

How Can Lodash's `_.groupBy` Function Efficiently Group Arrays of Objects by Key?

Barbara Streisand
Release: 2024-12-20 04:52:13
Original
402 people have browsed it

How Can Lodash's `_.groupBy` Function Efficiently Group Arrays of Objects by Key?

Grouping Objects in an Array by Key Using Lodash: A Practical Guide

Introduction

Grouping data in an organized manner is often a crucial task in various programming scenarios. When dealing with arrays of objects, it becomes necessary to group elements based on specific properties. Lodash, a popular JavaScript library, offers a powerful way to achieve this.

Lodash Solution

Lodash provides a handy method called _.groupBy that allows you to group an array of objects by a specified key. The usage is straightforward:

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

This will create a new object groupedCars where each key corresponds to a unique value of the make property from the cars array. The value for each key is an array of objects that share the same make value.

Implementation

Let's consider the example provided in the inquiry, where we have an array of car objects and desire to group them by make:

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' },
];
Copy after login

Using Lodash's _.groupBy method, we can create the desired grouped object as follows:

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

The resulting groupedCars object will be:

{
  audi: [
    { model: 'r8', year: '2012' },
    { model: 'rs5', year: '2013' },
  ],
  ford: [
    { model: 'mustang', year: '2012' },
    { model: 'fusion', year: '2015' },
  ],
  kia: [
    { model: 'optima', year: '2012' },
  ],
}
Copy after login

The above is the detailed content of How Can Lodash's `_.groupBy` Function Efficiently Group Arrays of Objects by Key?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template