Home > Web Front-end > JS Tutorial > How Can I Efficiently Group JavaScript Objects by a Key Using Lodash or Plain JavaScript?

How Can I Efficiently Group JavaScript Objects by a Key Using Lodash or Plain JavaScript?

Patricia Arquette
Release: 2025-01-04 12:18:38
Original
505 people have browsed it

How Can I Efficiently Group JavaScript Objects by a Key Using Lodash or Plain JavaScript?

Grouping Objects by Key with JavaScript and Lodash

Grouping objects based on a specific key is a common task when working with arrays of data. By grouping objects that share a common property, we can organize and access them more effectively.

One way to achieve this in plain JavaScript is to use the Array#reduce method. The following code snippet illustrates how:

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 result = cars.reduce(function (r, a) {
    r[a.make] = r[a.make] || [];
    r[a.make].push(a);
    return r;
}, {});

console.log(result);
Copy after login

This code uses the make property as the grouping key. It iterates through the array of cars and creates a new object with keys corresponding to the unique make values. For each make, it creates or appends an array of car objects sharing that make.

Lodash also provides a concise way to group objects using the _.groupBy function:

import { groupBy } from 'lodash';

const grouped = groupBy(cars, 'make');
Copy after login

The groupBy function takes two arguments: the array of objects and the property to group by. It returns a new object with keys corresponding to the unique values of the specified property, and values corresponding to arrays of objects sharing that value.

By grouping objects by key, we can easily access related data and perform operations on groups of objects with similar characteristics. This technique is particularly useful for optimizing data retrieval, filtering, and data visualization.

The above is the detailed content of How Can I Efficiently Group JavaScript Objects by a Key Using Lodash or Plain JavaScript?. 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