Home > Web Front-end > JS Tutorial > How to Group an Array of Objects by Key in JavaScript using Lodash or Plain JavaScript?

How to Group an Array of Objects by Key in JavaScript using Lodash or Plain JavaScript?

Linda Hamilton
Release: 2024-12-19 19:15:11
Original
916 people have browsed it

How to Group an Array of Objects by Key in JavaScript using Lodash or Plain JavaScript?

Grouping an Array of Objects by Key with Javascript and Lodash

Grouping objects in an array based on a specific key is a common operation. While Lodash provides a robust library for handling such tasks, it's also possible to achieve it with plain Javascript.

Consider the following array of car objects:

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

The goal is to create a new array of objects grouped by their 'make' property. Using plain Javascript, the following solution can be applied:

var result = cars.reduce(function (r, a) {
    r[a.make] = r[a.make] || [];
    r[a.make].push(a);
    return r;
}, Object.create(null));
Copy after login

This code leverages Array#reduce to iterate through the 'cars' array. For each object, it checks if an entry for its 'make' exists in the 'result' object. If not, it creates a new array for the 'make' and pushes the current object into it. If an entry already exists, it simply pushes the object into the array.

Lodash also offers a shortcut for this task:

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

The _.groupBy method takes an array and a property name and returns a new object where the keys are the values of the specified property and the values are arrays of the objects grouped by that property.

The above is the detailed content of How to Group an Array of Objects by Key in JavaScript 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