Home >Web Front-end >JS Tutorial >How Can I Group Objects in a JavaScript Array by a Shared Key?

How Can I Group Objects in a JavaScript Array by a Shared Key?

Barbara Streisand
Barbara StreisandOriginal
2024-12-26 16:40:10656browse

How Can I Group Objects in a JavaScript Array by a Shared Key?

Grouping Objects in Arrays by Key

In programming, it's often necessary to group objects within an array based on a shared key. Consider the following array of car objects as an example:

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

The goal is to create a new array where car objects are grouped by make. Using vanilla JavaScript, one approach is to employ the Array#reduce method along with an object:

const result = cars.reduce((r, a) => {
    r[a.make] = r[a.make] || [];
    r[a.make].push(a);
    return r;
}, Object.create(null));

console.log(result);

This code iterates through the cars array and checks if the current make exists as a key in the result object. If not, it adds the make as a key and initializes an empty array. It then pushes the current car object into the corresponding array, effectively grouping objects by their make.

The resulting result object will be structured as follows:

{
    'audi': [
        {
            'model': 'r8',
            'year': '2012'
        },
        {
            'model': 'rs5',
            'year': '2013'
        },
    ],

    'ford': [
        {
            'model': 'mustang',
            'year': '2012'
        },
        {
            'model': 'fusion',
            'year': '2015'
        }
    ],

    'kia': [
        {
            'model': 'optima',
            'year': '2012'
        }
    ]
}

The above is the detailed content of How Can I Group Objects in a JavaScript Array by a Shared Key?. 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