Group by element in array JavaScript

Grouping array elements by a specific property is a common JavaScript task. This tutorial shows how to group an array of objects by their uuid property into separate sub-arrays.

Problem Statement

Given an array of objects with similar properties, we need to group them by a specific key and return an array of arrays.

const arr = [
    {"name": "toto", "uuid": 1111},
    {"name": "tata", "uuid": 2222},
    {"name": "titi", "uuid": 1111}
];
console.log("Original array:", arr);
Original array: [
  { name: 'toto', uuid: 1111 },
  { name: 'tata', uuid: 2222 },
  { name: 'titi', uuid: 1111 }
]

Expected Output

We want to group objects with the same uuid into sub-arrays:

const expectedOutput = [
    [
        {"name": "toto", "uuid": 1111},
        {"name": "titi", "uuid": 1111}
    ],
    [
        {"name": "tata", "uuid": 2222}
    ]
];

Solution Using forEach and Hash Map

const arr = [
    {"name": "toto", "uuid": 1111},
    {"name": "tata", "uuid": 2222},
    {"name": "titi", "uuid": 1111}
];

const groupByElement = arr => {
    const hash = Object.create(null);
    const result = [];
    
    arr.forEach(el => {
        if (!hash[el.uuid]) {
            hash[el.uuid] = [];
            result.push(hash[el.uuid]);
        }
        hash[el.uuid].push(el);
    });
    
    return result;
};

console.log(groupByElement(arr));
[
  [ { name: 'toto', uuid: 1111 }, { name: 'titi', uuid: 1111 } ],
  [ { name: 'tata', uuid: 2222 } ]
]

Alternative Solution Using reduce()

const groupByProperty = (arr, property) => {
    const grouped = arr.reduce((acc, item) => {
        const key = item[property];
        if (!acc[key]) {
            acc[key] = [];
        }
        acc[key].push(item);
        return acc;
    }, {});
    
    return Object.values(grouped);
};

const arr = [
    {"name": "toto", "uuid": 1111},
    {"name": "tata", "uuid": 2222},
    {"name": "titi", "uuid": 1111}
];

console.log(groupByProperty(arr, 'uuid'));
[
  [ { name: 'toto', uuid: 1111 }, { name: 'titi', uuid: 1111 } ],
  [ { name: 'tata', uuid: 2222 } ]
]

How It Works

Both solutions use a hash map approach:

  1. Create an empty hash object to track groups
  2. Iterate through each array element
  3. Use the grouping property as the hash key
  4. If the key doesn't exist, create a new array for that group
  5. Add the current element to its corresponding group
  6. Return the grouped arrays

Comparison

Method Flexibility Readability Performance
forEach + Hash Fixed property Good Fast
reduce() Dynamic property Better Fast

Conclusion

Both methods efficiently group array elements by a property. The reduce() approach offers more flexibility by accepting the property name as a parameter, making it reusable for different grouping scenarios.

Updated on: 2026-03-15T23:19:00+05:30

478 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements